62

How to print just the last line of a file?

PJ Brunet
  • 3,615
  • 40
  • 37
yael
  • 2,765
  • 10
  • 40
  • 48

5 Answers5

118
$ cat file | awk 'END{print}'

Originally answered by Ventero

PJ Brunet
  • 3,615
  • 40
  • 37
Joey
  • 344,408
  • 85
  • 689
  • 683
  • 2
    I 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
32

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

Kryten
  • 15,230
  • 6
  • 45
  • 68
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
14

Is it a must to use awk for this? Why not just use tail -n 1 myFile ?

RonK
  • 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
  • 1
    I 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
8

Find out the last line of a file:

  1. Using sed (stream editor): sed -n '$p' fileName

  2. Using tail: tail -1 fileName

  3. using awk: awk 'END { print }' fileName

Lucas Zamboulis
  • 2,494
  • 5
  • 24
  • 27
rishabh
  • 81
  • 1
  • 1
7

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.

cmaher
  • 5,100
  • 1
  • 22
  • 34
Tapan Avasthi
  • 89
  • 1
  • 4