Print the last line of a file, from the CLI

95,279

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:

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

  2. Using tail: tail -1 fileName

  3. 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.

Share:
95,279
yael
Author by

yael

Updated on April 22, 2020

Comments

  • yael
    yael about 4 years

    How to print just the last line of a file?

  • Michael Mrozek
    Michael Mrozek about 14 years
    @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
  • ghostdog74
    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
    Tomasz Gandor almost 10 years
    @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.
  • jake
    jake over 9 years
    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"
  • wukong
    wukong over 5 years
    what's the meaning of -n and $p?
  • philraj
    philraj almost 5 years
    @wukong -n means don't print each line by default, $p means for the last line ($) execute the command p (print).
  • PJ Brunet
    PJ Brunet about 4 years
    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.