How to print just the last line of a file?
5 Answers
$ cat file | awk 'END{print}'
Originally answered by Ventero
- 
                    2I 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. – PJ Brunet Apr 22 '20 at 06:52
 
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
- 15,230
 - 6
 - 45
 - 68
 
- 327,991
 - 56
 - 259
 - 343
 
Is it a must to use awk for this? Why not just use tail -n 1 myFile ?
- 9,472
 - 8
 - 51
 - 87
 
- 
                    6@yael Not at all; `tail -1` will be way faster than `awk` for a large file. I tried on an ~3m line file; tail was instantaneous while awk took .44s – Michael Mrozek Jun 20 '10 at 19:54
 - 
                    2@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. – ghostdog74 Jun 21 '10 at 10:48
 - 
                    @yael is right - in the sence that `awk` (3B) is faster to type than `tail` (4B). When it comes to speed - well `tail` 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 mention `tail -n +N`. – Tomasz Gandor Aug 01 '14 at 08:08
 - 
                    1I 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" – jake Dec 09 '14 at 15:26
 
Find out the last line of a file:
Using sed (stream editor):
sed -n '$p' fileNameUsing tail:
tail -1 fileNameusing awk:
awk 'END { print }' fileName
- 2,494
 - 5
 - 24
 - 27
 
- 81
 - 1
 - 1
 
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.
- 5,100
 - 1
 - 22
 - 34
 
- 89
 - 1
 - 4
 
- 
                    
 - 
                    @wukong `-n` means don't print each line by default, `$p` means for the last line (`$`) execute the command `p` (print). – philraj Sep 17 '19 at 15:45