Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

first two results from ls command

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.

like image 764
Fidel Avatar asked May 09 '12 16:05

Fidel


People also ask

What is the result of the command ls?

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.

What is the first details of ls L output?

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.

What is the output of ls?

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.


2 Answers

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.

like image 126
dag Avatar answered Oct 05 '22 03:10

dag


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.

like image 28
Stephen P Avatar answered Oct 05 '22 03:10

Stephen P