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.
The ls command writes to standard output the contents of each specified Directory parameter or the name of each specified File parameter, along with any other information you ask for with the flags. If you do not specify a File or Directory parameter, the ls command displays the contents of the current directory.
The ls –l command and Permissions in Linux The output contains the following information: Type of file (This is the first character and specifies if the file is a directory, file, character device, or block device) Permissions (The next 9 characters in three groups of three.
The default output of the ls command shows only the names of the files and directories, which is not very informative. The -l ( lowercase L) option tells ls to print files in a long listing format. When the long listing format is used, you can see the following file information: The file type.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With