16

Supposed I make a listing and sort the files by its temporal attribute:

ls -ltr

-rwxrwxrwx 1 bla bla 4096 Feb 01 20:10 foo1
-rwxrwxrwx 1 bla bla 4096 Feb 01 20:12 foo2
.
.
.
-rwxrwxrwx 1 bla bla 4096 Mar 05 13:25 foo1000

What should I add behind the ls -ltr in a pipe chain in order to obtain only the last line of the listing ? I know there are sed and awk, but I do not know how to use them, I only know what they can do.

1

3 Answers 3

29

Since you asked about sed specifically,

ls -ltr | sed '$!d'
2
  • thank you, i am now a little proud having learned some concrete sed. Mar 26, 2015 at 22:35
  • 6
    Also, sed -n '$p' does the same thing, but really tail -1 is the right tool for the job.
    – imiric
    Jul 9, 2017 at 19:39
15

You're looking for tail :

ls -ltr | tail -n 1

This will display only the last line of ls -ltr's output. You can control the number of lines by changing the value after -n; if you omit -n 1 entirely you'll get ten lines.

The benefit of using tail instead of sed is that tail starts at the end of the file until it reaches a newline, while sed would have to traverse the whole file until it reaches the end, and only then return the text since the last newline was found.

3
5

With awk:

ls -ltr | awk 'END { print }'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .