311

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

Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
Doboy
  • 10,411
  • 11
  • 40
  • 48

11 Answers11

574

You don't need cat.

head -1 file

will work fine.

Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
93

You don't, use head instead.

head -n 1 file.txt
Orbling
  • 20,413
  • 3
  • 53
  • 64
48

There are many different ways:

sed -n 1p file
head -n 1 file
awk 'NR==1' file
JJJ
  • 489
  • 4
  • 2
26

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

Mike Pelley
  • 2,939
  • 22
  • 23
17

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
mwcz
  • 8,949
  • 10
  • 42
  • 63
12

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

 cat <file> | awk 'NR == 1'
josh.trow
  • 4,861
  • 20
  • 31
  • 2
    I suppose it's silly to call out a 'useless use of cat' on a line specifically designed to use `cat`, isn't it. – jkerian May 24 '11 at 19:20
  • This method is great because you can pick any line you want. – desgua Nov 28 '13 at 09:14
  • 3
    @desgua `awk` is great, but you don't need `cat` here. `awk 'NR == 2 {print $0}' ` does the same thing. (And much more, if you learn a little `awk`. – Eric Wilson Jun 25 '15 at 13:36
6

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.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
3

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

head -1 FileName.csv
Yogi Ghorecha
  • 1,584
  • 1
  • 19
  • 26
3

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

:)

clt60
  • 62,119
  • 17
  • 107
  • 194
2

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
Norfeldt
  • 8,272
  • 23
  • 96
  • 152
0

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'
ardnew
  • 2,028
  • 20
  • 29