0

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

cody
  • 11,045
  • 3
  • 21
  • 36
Lava Sangeetham
  • 2,943
  • 4
  • 38
  • 54

2 Answers2

2

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

gregory
  • 10,969
  • 2
  • 30
  • 42
0

If you're using bash, the following is an option for getting grep results sorted by modification date:

while IFS= read -r -d '' file; do
    grep -H "keyword" "$file"
done < <(find * -type f -printf "%T@\t%p\0" | sort -rz | cut -z -f2-)

A breakdown of the find expression:

find * -type f -printf "%T@\t%p\0" |    # print last-mod date and filename, NUL-terminated
    sort -rz |                          # sort in reverse order
    cut -z -f2-                         # cut out time field
cody
  • 11,045
  • 3
  • 21
  • 36