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.
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.
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.
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.
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.
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
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
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