Bash – How to Tail Last 4 Modified Files

bashterminal

I feel like I am missing something very simple and I was wondering if it possible to sow the last few lines of the last 4 modified files. I tried something like this

tail | ls -lt | head -5

but I think I should iterate over ls | -lt result and apply tail to it and I am not sure how to do it. Any help is appreciated

Best Answer

Before I start, it’s generally considered bad practice to use the output of ls as input for something else; a common flaw being that it may not work as intended for files containing white space/new line in their name.

With that limitation in mind, you will probably find that ls | something will work OK most of the time.

You are heading in the right direction with your command, here is one solution with the above caveat about ls limitations:

ls -t | head -5 | xargs tail

This will throw a non fatal error if there are subdirectories in your listing.

Related Question