Search code examples
bashgrepag

Grep keyword in multiple files and sort results by files modified date or name


Trying to search a key word in multiple files. but search results are not sorted by files modified date or name

ag grep tool:

ag "keyword"

grep tool:

grep -r "keyword"

is there any way we can control the results sort by files modified date or name like following?

Expected Output:

File_0.txt: search results

File_1.txt: search results

File_2.txt: search results


Solution

  • Just sort with ls and pass the results into grep or ag, e.g. to sort by date:

    grep "keyword" $(ls -1rt)

    To sort by name, agin use ls. A caveat worth mentioning for the MacOS: you'll need to use GNU's ls (brew install coreutils) with its -U flag:

    ag "keyword" $(gls -U --color) #sort by name on MacOS