1. Overview

We use the ls command in Linux to list our files and folders. We can add options to display more or less detail. It also lets us sort our files on the last modified time.

A common use case is that we want, let’s say, the five files that were last modified. Unfortunately, ls alone can’t limit its output. In this tutorial, we’re going to use ls together with head and tail to accomplish this.

The examples in this article were all tested in bash but should also work in other shells.

2. Listing Last Modified Files

Assume we have a directory containing ten files named file-1.txt, file-2.txt up until file-10.txt. They have been created in the same order. Using ls -t, we can list them by the last modified time:

$ ls -t1
file-10.txt
file-9.txt
file-8.txt
file-7.txt
file-6.txt
file-5.txt
file-4.txt
file-3.txt
file-2.txt
file-1.txt

As expected, this prints the files in the reverse order by which we created them. Note that we also added 1 as an argument to ls we get each file on its own line.

3. Using head

Now to limit the result to only the five last modified files, we pipe the output of ls through head:

$ ls -t1 | head -5
file-10.txt
file-9.txt
file-8.txt
file-7.txt
file-6.txt

4. Using tail

When we want to know what files have been least recently modified, we use tail to grab the last five results:

$ ls -t1 | tail -5
file-5.txt
file-4.txt
file-3.txt
file-2.txt
file-1.txt

5. Reverse Ordering

Using a tail to grab the last five results might not give us the result we want. We probably want to list the oldest file first. Let’s add r to the arguments of ls to apply reverse ordering:

$ ls -tr1 | tail -5
file-6.txt
file-7.txt
file-8.txt
file-9.txt
file-10.txt

This has printed the last modified files in reverse order of creation. The ordering of ls is done before the output is piped through tail. We must replace this last command with head to get the result we want:

$ ls -tr1 | head -5
file-1.txt
file-2.txt
file-3.txt
file-4.txt
file-5.txt

6. Conclusion

In this article, we learned how to combine the ls command with head to show us the five last modified files in a directory. We also learned we could use ls along with tail when we desire the opposite.

By sorting reversing the output of ls, we can further tailor the result to our liking.

Comments are closed on this article!