first two results from ls command

LinuxSearchLimitLs

Linux Problem Overview


I am using ls -l -t to get a list of files in a directory ordered by time.

I would like to limit the search result to the top 2 files in the list.
Is this possible?
I've tried with grep and I struggled.

Linux Solutions


Solution 1 - Linux

You can pipe it into head:

ls -l -t | head -3

Will give you top 3 lines (2 files and the total).

This will just give you the first 2 lines of files, skipping the size line:

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

tail strips the first line, then head outputs the next 2 lines.

Solution 2 - Linux

To avoid dealing with the top output line you can reverse the sort and get the last two lines

ls -ltr | tail -2

This is pretty safe, but depending what you'll do with those two file entries after you find them, you should read Parsing ls on the problems with using ls to get files and file information.

Solution 3 - Linux

Or you could try just this

ls -1 -t | head -2

The -1 switch skips the title line.

Solution 4 - Linux

You can use the head command to grab only the first two lines of output:

ls -l -t | head -2

Solution 5 - Linux

You have to pipe through head.

> ls -l -t | head -n 3

will output the two first results.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFidelView Question on Stackoverflow
Solution 1 - LinuxdagView Answer on Stackoverflow
Solution 2 - LinuxStephen PView Answer on Stackoverflow
Solution 3 - LinuxSaad Rehman ShahView Answer on Stackoverflow
Solution 4 - LinuxlarsksView Answer on Stackoverflow
Solution 5 - LinuxPier-Alexandre BouchardView Answer on Stackoverflow