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.

3 Answers3

29

Since you asked about sed specifically,

ls -ltr | sed '$!d'
steeldriver
  • 81,074
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.

Stephen Kitt
  • 434,908
5

With awk:

ls -ltr | awk 'END { print }'
taliezin
  • 9,275