How to get the first line of a file in a bash script?

前端 未结 6 1856
不思量自难忘°
不思量自难忘° 2020-12-04 06:59

I have to put in a bash variable the first line of a file. I guess it is with the grep command, but it is any way to restrict the number of lines?

6条回答
  •  星月不相逢
    2020-12-04 07:49

    This suffices and stores the first line of filename in the variable $line:

    read -r line < filename
    

    I also like awk for this:

    awk 'NR==1 {print; exit}' file
    

    To store the line itself, use the var=$(command) syntax. In this case, line=$(awk 'NR==1 {print; exit}' file).

    Or even sed:

    sed -n '1p' file
    

    With the equivalent line=$(sed -n '1p' file).


    See a sample when we feed the read with seq 10, that is, a sequence of numbers from 1 to 10:

    $ read -r line < <(seq 10) 
    $ echo "$line"
    1
    
    $ line=$(awk 'NR==1 {print; exit}' <(seq 10))
    $ echo "$line"
    1
    

提交回复
热议问题