MilMike
MilMike

Reputation: 12831

How to show filename when AWK found matches?

I have a small script that searches all txt files for a string and outputs the matches. Is there a way to show the filename above the match but only when a match was found? Currently I am using this:

find . -iname "*.txt" -print0 | xargs -0 awk -v RS='' 'tolower($0) ~ /cool/;'

I tried to add FILENAME to the end of the script but now it only displays the filename and not the matches:

find . -iname "*.txt" -print0 | xargs -0 awk -v RS='' 'tolower($0) ~ /cool/{print FILENAME};' 

Upvotes: 1

Views: 2804

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

There's a much more simple way with grep one-liner:

grep -rio 'cool' --include=*.txt
  • -r - process recursively

  • -i - ignore case

  • -o - print only matched substrings/parts

  • --include=*.txt - search only files whose name matches *.txt


The output should contain filename and matched/found part in format:

<filename1>.txt:cool
<filename2>.txt:cOol
<filename3>.txt:COOL
...

Upvotes: 3

karakfa
karakfa

Reputation: 67497

you're not printing the line, change to

   ... {print $0, FILENAME} ...

print without arguments means print $0, and default statement is {print} when missing as in your first script.

Upvotes: 4

Related Questions