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.

Abdul Al Hazred
  • 25,760
  • 23
  • 64
  • 88
  • [Why *not* parse `ls` (and what to do instead)?](https://unix.stackexchange.com/q/128985/44425), http://mywiki.wooledge.org/ParsingLs – phuclv Feb 06 '23 at 01:22

3 Answers3

29

Since you asked about sed specifically,

ls -ltr | sed '$!d'
steeldriver
  • 78,509
  • 12
  • 109
  • 152
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
  • 411,918
  • 54
  • 1,065
  • 1,164
  • perfect, very quick and helpful answer – Abdul Al Hazred Mar 26 '15 at 22:19
  • `tail -1` ... `-n` is redundant. – dhchdhd Sep 20 '18 at 00:00
  • 1
    @Barry `tail -1` is deprecated (see the “RATIONALE” section of [the POSIX specification for `tail`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/tail.html), or the last part of [the GNU `tails` manual](https://www.gnu.org/software/coreutils/manual/html_node/tail-invocation.html)); it still works in this case, for now, but it’s best to avoid using it in examples. – Stephen Kitt Sep 20 '18 at 04:13
5

With awk:

ls -ltr | awk 'END { print }'
taliezin
  • 9,085
  • 1
  • 34
  • 38