grep for file content but return the filename

3

2

I need the GREP syntax for the following task (am in a LINUX OS):

querying ALL files in the CURRENT directory which contain STRING but only listing the FILENAMES which contain a match.

Thanks!

Allan Bowe

Posted 2012-09-06T12:36:19.510

Reputation: 133

I think this crosses the line and isn't a programming question. Voting for move to Super User. – unwind – 2012-09-06T12:38:20.933

I disagree - for me it is common to embed OS commands in other languages. – Allan Bowe – 2012-09-06T12:53:03.503

Answers

9

You can use

grep -rl stringToSearch .

or

 find . -type f -exec grep -l stringToSearch {} \;

For more info on grep and other unix command, please refer to manual ( man )

In that case man grep says that

-l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed.
The scanning will stop on the first match.

Obviously, as a bash command, if your string contains special chars or spaces, you have to (in order) escape them and/or surrounding your string with quotas

DonCallisto

Posted 2012-09-06T12:36:19.510

Reputation: 246

1

"Grep -l" wil give you the list of file names.

> echo "hello" > test_file1.list
> echo "hello2.." > test_file2.list
> echo "xyz" > test_file3.list


> grep "hello" test_file*list

test_file1.list:hello
test_file2.list:hello2..


> grep -l "hello" test_file*list
test_file1.list
test_file2.list

Rajesh Chamarthi

Posted 2012-09-06T12:36:19.510

Reputation: 111