Coder Perfect

the first two outputs of the ls command


I’m getting a list of files in a directory ordered by time using ls -l -t.

I’d like the search results to be limited to the top two files in the list. Is that even possible? I tried grep and failed miserably.

Asked by Fidel

Solution #1

You may pipe it into your skull like this:

ls -l -t | head -3

I’ll give you the top three lines (2 files and the total).

The first two lines of files will be returned, with the size line skipped:

ls -l -t | tail -n +2 | head -2

The first line is stripped by tail, and the next two lines are output by head.

Answered by dag

Solution #2

You can reverse the sort to get the last two lines and avoid dealing with the top output line.

ls -ltr | tail -2

This is rather safe, but depending on what you plan to do with those two file entries once you’ve located them, you should read Parsing ls for more information on the issues with using ls to obtain files and file information.

Answered by Stephen P

Solution #3

You could also try simply this.

ls -1 -t | head -2

The -1 switch removes the title line from the equation.

Answered by Saad Rehman Shah

Solution #4

Only the first two lines of output can be grabbed with the head command:

ls -l -t | head -2

Answered by larsks

Solution #5

You must pipe through the head.

will print the first two results

Answered by Pier-Alexandre Bouchard

Post is based on