littleK
littleK

Reputation: 20163

Using grep to search for instances of a string in all files within a directory, using PHP bash script

I am writing a PHP command line script, and I'm wondering if any grep experts can help me to come up with a command to do the following:

For all files ending in .java in the current directory ($curDir), search within the file for any instance of $str, and return an indicator whether any instance has been found or not.

I've tried piecing together a grep command from various bits found on the internet but, having not really used grep before, its a bit difficult to piece together. I would appreciate any help.

Thanks!

Upvotes: 0

Views: 1995

Answers (2)

evan
evan

Reputation: 12553

This should do the trick:

exec("grep '$str' *.java", $output_array);

Use -l if you want it to just output the file names. Other grep options can be found here:
http://unixhelp.ed.ac.uk/CGI/man-cgi?grep

Depending on what $str is you may need to pass it through: escapeshellarg():
http://www.php.net/manual/en/function.escapeshellarg.php

Upvotes: 1

Billy
Billy

Reputation: 1253

Grep is well suited to that task.

grep -rl '$str' .

That command will report file names of files that match your string. It will only report each file name once but that seems to be what you want. The option "-r" says to recursively traverse the file system and the option "-l" says to just report file that contain a match. You may also want to check out the options "-H" and "-n" as I use them frequently.

Upvotes: 0

Related Questions