Does anyone know of a simple one liner to read the first line of a file in bash?
5 Answers
read -r FIRSTLINE < filename
Same result as the other answers but faster because it doesn't spawn any process, as "read" is a built-in bash command.
-
-
This performs much better than doing 'head -n 1'. I was reading the first line of 265 files and my time went from approximately 15 seconds to less than 1 second– s3v1Nov 25, 2014 at 14:32
head -1
simply
-
-
There few to explain .. simply does what the questions asks :) Retain 1 line at the beginning of a file– drAlberTFeb 12, 2023 at 11:15
FIRSTLINE=`head -n 1 filename`
Stores the line in a variable for later use (note the inverted apostrophes).
-
5$(command) is an alternate form that avoid the use of back ticks, not even simple to be found on certain keyboards.– drAlberTSep 18, 2009 at 8:48
-
1good answer, but I'm voting down because e-t172's answer is better. Read is intended for this, and it's built-in to bash, as he says.– Lee BSep 18, 2009 at 10:13
-
2nah, voting down a "good answer" becouse it is not the best possible is not so polite don't you think?– drAlberTSep 18, 2009 at 13:16
-
3Lee - Why not just upvote the one you like instead? Downvotes should only be given for factually incorrect information or off topic stuff.– MDMarraSep 19, 2009 at 2:53
awk 'NR == 1' /etc/passwd
-
2this will scan full file, then return the first line, which is inefficient for large file. read -r is better.– RichardMar 12, 2012 at 18:24
-
awk '{ print; exit; }'
will return the first line without reading the whole file, so if you cannot useread -r
(e.g. because you are not reading into a variable) and don't want to use head for some reason (e.g. it sometimes fails with exit code 141, as it does for me) then that's theawk
equivalent.– EM0Oct 24, 2022 at 9:18