How do I read the first line of a file using cat?

前端 未结 11 779
渐次进展
渐次进展 2021-01-29 22:20

How do I read the first line of a file using cat?

相关标签:
11条回答
  • 2021-01-29 22:31

    You dont need any external command if you have bash v4+

    < file.txt mapfile -n1 && echo ${MAPFILE[0]}
    

    or if you really want cat

    cat file.txt | mapfile -n1 && echo ${MAPFILE[0]}
    

    :)

    0 讨论(0)
  • 2021-01-29 22:35

    I'm surprised that this question has been around as long as it has, and nobody has provided the pre-mapfile built-in approach yet.

    IFS= read -r first_line <file
    

    ...puts the first line of the file in the variable expanded by "$first_line", easy as that.

    Moreover, because read is built into bash and this usage requires no subshell, it's significantly more efficient than approaches involving subprocesses such as head or awk.

    0 讨论(0)
  • 2021-01-29 22:36

    There are many different ways:

    sed -n 1p file
    head -n 1 file
    awk 'NR==1' file
    
    0 讨论(0)
  • 2021-01-29 22:36

    There is plenty of good answer to this question. Just gonna drop another one into the basket if you wish to do it with lolcat

    lolcat FileName.csv | head -n 1
    
    0 讨论(0)
  • 2021-01-29 22:37

    Adding one more obnoxious alternative to the list:

    perl -pe'$.<=1||last' file
    # or 
    perl -pe'$.<=1||last' < file
    # or
    cat file | perl -pe'$.<=1||last'
    
    0 讨论(0)
  • 2021-01-29 22:38

    This may not be possible with cat. Is there a reason you have to use cat?

    If you simply need to do it with a bash command, this should work for you:

    head -n 1 file.txt
    
    0 讨论(0)
提交回复
热议问题