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

BashFile IoCat

Bash Problem Overview


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

Bash Solutions


Solution 1 - Bash

You don't need cat.

head -1 file

will work fine.

Solution 2 - Bash

You don't, use head instead.

head -n 1 file.txt

Solution 3 - Bash

There are many different ways:

sed -n 1p file
head -n 1 file
awk 'NR==1' file


Solution 4 - Bash

You could use cat file.txt | head -1, but it would probably be better to use head directly, as in head -1 file.txt.

Solution 5 - Bash

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

Solution 6 - Bash

cat alone may not be possible, but if you don't want to use head this works:

 cat <file> | awk 'NR == 1'

Solution 7 - Bash

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.

Solution 8 - Bash

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]}

:)

Solution 9 - Bash

Use the below command to get the first row from a CSV file or any file formats.

head -1 FileName.csv

Solution 10 - Bash

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

Solution 11 - Bash

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'

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
QuestionDoboyView Question on Stackoverflow
Solution 1 - BashCarl NorumView Answer on Stackoverflow
Solution 2 - BashOrblingView Answer on Stackoverflow
Solution 3 - BashJJJView Answer on Stackoverflow
Solution 4 - BashMike PelleyView Answer on Stackoverflow
Solution 5 - BashmwczView Answer on Stackoverflow
Solution 6 - Bashjosh.trowView Answer on Stackoverflow
Solution 7 - BashCharles DuffyView Answer on Stackoverflow
Solution 8 - Bashjm666View Answer on Stackoverflow
Solution 9 - BashPraveenkumar SekarView Answer on Stackoverflow
Solution 10 - BashNorfeldtView Answer on Stackoverflow
Solution 11 - BashardnewView Answer on Stackoverflow