David E
David E

Reputation: 37

Sort files then pass them to awk for search

I want to search through a list of files and get a list of the results. For that I have:

awk 'tolower($0) ~ /hauerwas/' RS= ORS="\\n\\n**********************\\n\\n" *

Works good except the results are in the wrong order. I want the results from the newer FILES on top. Not sort the results, but sort the files then search them.

So I tried to create a variable from an 'ls' command sorted the way I want, then run the awk on each file in the variable. This is what I have:

theFile=`ls -r`; for file in "$theFile"; do awk 'tolower($0) ~ /hauerwas/' "$file"; done

Doesn't work. Just spits on a listing of the files.

Any help would be amazing.

Upvotes: 0

Views: 117

Answers (2)

jthill
jthill

Reputation: 60443

for file in "$theFile"

The quotes shut off wordsplitting, if you know there's no white space in your file names just lose them; otherwise you'll do better with something like

find -type f -exec ls -t {} + \
| xargs -d\\n awk 'tolower($0)~/hauerwas/' RS= ORS=$'\n\n**********************\n\n'

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 247042

You could do (assuming GNU tools, and assuming none of your filenames contain newlines)

mapfile -t sortedByMtimeDesc < <(stat -c '%Y %n' * | sort -nr | cut -d " " -f 2-)
awk ... "${sortedByMtimeDesc[@]}"

Upvotes: 2

Related Questions