Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort the output of "grep -l" chronologically by newest modification date last?

Tags:

linux

grep

unix

I'm using the -l flag with grep to just print the matching file names.

I want to then list the results (files) in ascending order i.e. newest last.

Obviously

grep -l <pattern> *.txt | ls -rt

is not what I need, since the ls -lrt merely outputs all files.

like image 625
Pyderman Avatar asked Jul 09 '12 09:07

Pyderman


People also ask

How do I sort grep output?

To sort anything you need to use the sort command. You can use grep to identify the lines to sort, then pipe the output to sort and use the -h switch for a numeric sort with -k identifying what column to sort on.

Which command will sort the files by their modification time?

ls command ls – Listing contents of directory, this utility can list the files and directories and can even list all the status information about them including: date and time of modification or access, permissions, size, owner, group etc.

Does grep modify?

Search and edit text files by using the following commands. grep: The grep command allows you to search inside a number of files for a particular search pattern and then print matching lines.


3 Answers

Try:

ls -rt *.txt | xargs grep -l <pattern>

We first use ls to list *.txt files and sort them by modification time (newest last), then for each entry run them through grep so we only print out files that contain the pattern.

like image 164
Shawn Chin Avatar answered Oct 12 '22 19:10

Shawn Chin


Here is another way

grep -l <pattern> *.txt | xargs ls -ltr --time-style="+%Y%m%d_%H%M"

For example

$ grep -l argparse * | xargs ls -ltr --time-style="+%Y%m%d_%H%M"
-rwxr-xr-x 1 raju 197121   979 20171030_2323 list_dep.py
-rwxr-xr-x 1 raju 197121 14329 20180129_2216 grep_installed.py
-rwxr-xr-x 1 raju 197121  7517 20180129_2216 popsort.py

To just list the files without timestamps etc.,

grep -l <pattern> * | xargs ls -1tr

For example

$ grep -l argparse * | xargs ls -1tr
list_dep.py
grep_installed.py
popsort.py
like image 38
Kamaraju Kusumanchi Avatar answered Oct 12 '22 18:10

Kamaraju Kusumanchi


I know this is an old question but thought of adding my suggestion for someone who is searching for the same..

for i in $(ls -rt *.txt); do grep <pattern> $i; done

like image 20
NIK Avatar answered Oct 12 '22 18:10

NIK