yons88
yons88

Reputation: 459

Write a shell script that find-greps files and outputs only those filenames

I want to search files in particular folder and content, then I want to print only the name of the files found. I have a command:

for file in $(find from | xargs grep 'move')
do 
   echo $file
done

It prints eg:

from/1.txt:move
from/2.txt:some text
move
from/3.txt:move text

But I want:

from/1.txt
from/2.txt
from/3.txt

I tried to cut that unnecessary part by using:

${file%:*}

this gives result:

from/1.txt
from/2.txt
move
from/3.txt

That 'move' is left.

Upvotes: 0

Views: 972

Answers (2)

Malcolm
Malcolm

Reputation: 1259

Grep has a recursive as well as a 'just list filename' option, so this should work:

grep -r -l "move" from

Upvotes: 3

nosid
nosid

Reputation: 50124

Use the option -l to grep, i.e.

for file in $(find from | xargs grep -l 'move')
do 
   echo $file
done

Or even better:

for file in $(find from -type f -print0 | xargs -r0 grep -l 'move')
do 
   echo $file
done

Upvotes: 2

Related Questions