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

Bash

Bash Problem Overview


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?

Bash Solutions


Solution 1 - Bash

head takes the first lines from a file, and the -n parameter can be used to specify how many lines should be extracted:

line=$(head -n 1 filename)

Solution 2 - Bash

to read first line using bash, use read statement. eg

read -r firstline<file

firstline will be your variable (No need to assign to another)

Solution 3 - Bash

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

Solution 4 - Bash

line=$(head -1 file)

Will work fine. (As previous answer). But

line=$(read -r FIRSTLINE < filename)

will be marginally faster as read is a built-in bash command.

Solution 5 - Bash

Just echo the first list of your source file into your target file.

echo $(head -n 1 source.txt) > target.txt

Solution 6 - Bash

The question didn't ask which is fastest, but to add to the sed answer, -n '1p' is badly performing as the pattern space is still scanned on large files. Out of curiosity I found that 'head' wins over sed narrowly:

# best:
head -n1 $bigfile >/dev/null

# a bit slower than head (I saw about 10% difference):
sed '1q' $bigfile >/dev/null

# VERY slow:
sed -n '1p' $bigfile >/dev/null

Solution 7 - Bash

Read only the first line of a file and store it into a variable:

read var < file

echo $var # print only the first line of 'file'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNeuquinoView Question on Stackoverflow
Solution 1 - BashsthView Answer on Stackoverflow
Solution 2 - Bashghostdog74View Answer on Stackoverflow
Solution 3 - BashfedorquiView Answer on Stackoverflow
Solution 4 - BashjackbotView Answer on Stackoverflow
Solution 5 - BashopenwonkView Answer on Stackoverflow
Solution 6 - BashGoblinhackView Answer on Stackoverflow
Solution 7 - BashGrégori Fernandes de LimaView Answer on Stackoverflow