Print the last line of a file, from the CLI
Solution 1
$ cat file | awk 'END{print}'
Originally answered by Ventero
Solution 2
Use the right tool for the job. Since you want to get the last line of a file, tail is the appropriate tool for the job, especially if you have a large file. Tail's file processing algorithm is more efficient in this case.
tail -n 1 file
If you really want to use awk,
awk 'END{print}' file
EDIT : tail -1 file
deprecated
Solution 3
Is it a must to use awk
for this? Why not just use tail -n 1 myFile
?
Solution 4
Find out the last line of a file:
Using sed (stream editor):
sed -n '$p' fileName
Using tail:
tail -1 fileName
using awk:
awk 'END { print }' fileName
Solution 5
You can achieve this using sed
as well. However, I personally recommend using tail
or awk
.
Anyway, if you wish to do by sed
, here are two ways:
Method 1:
sed '$!d' filename
Method2:
sed -n '$p' filename
Here, filename is the name of the file that has data to be analysed.
yael
Updated on April 22, 2020Comments
-
yael about 4 years
How to print just the last line of a file?
-
Michael Mrozek about 14 years@yael Not at all;
tail -1
will be way faster thanawk
for a large file. I tried on an ~3m line file; tail was instantaneous while awk took .44s -
ghostdog74 about 14 years@yael. tail is specifically meant for processing the file from the "end". Therefore, its faster than awk. Because awk processes files from the beginning. The algorithms are different.
-
Tomasz Gandor almost 10 years@yael is right - in the sence that
awk
(3B) is faster to type thantail
(4B). When it comes to speed - welltail
has a simpler task, and no script to parse before execution. However, @ghostdog74 is not right about "working from the end". If the input is piped,tail
also needs to work from the beginning. And not to mentiontail -n +N
. -
jake over 9 yearsI wanted the first field of the last line of the file (
awk 'END { print $1 }'
). While it's not what the OP asked, the question helped and was easier to search for than "first field of last line of file" -
wukong over 5 yearswhat's the meaning of
-n
and$p
? -
philraj almost 5 years@wukong
-n
means don't print each line by default,$p
means for the last line ($
) execute the commandp
(print). -
PJ Brunet about 4 yearsI think the original question specified "awk" but since the question changed to be more generic, this answer made no sense. So I improved the answer a little bit. Overall, "tail" is a great solution, but "awk" might offer more nuanced control.