Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Long story short, I got a folder with nearly 800,000 php files. I would like to search each file for a string and if it exists in that file, the file gets copied to another directory.

Is this possible from the terminal?

So far I got:

grep -i -n -r 'ppr-1792' * | cp $1 move_to_here

But this obviously doesn't work. $1 needs to be the file name that contains matching text.

What should I do?

share|improve this question
up vote 0 down vote accepted

You can use a for loop and test the return code of grep, or use grep -c (count matches) and see if the match count is greater than 1.


for i in *
    grep -i -n 'Power' "$i"

    if [ "$?" -eq 0 ]
            cp "$i" mvd
share|improve this answer
Thanks. I get the error "bash: syntax error near unexpected token `fi'". I'm pasting that directly into the terminal. Is that correct? – Jarrod Feb 3 '11 at 3:24
To be safe, you should probably quote all variables; e.g.: "$i" – farfromhome Feb 3 '11 at 3:27
Oh, and you forgot the ; then after the (what should be) if [ $? -eq 0 ] – farfromhome Feb 3 '11 at 3:28
sorry, where does the ';' go? after "done"? – Jarrod Feb 3 '11 at 3:30
if grep -inqs 'Power' "$i"; then – grawity Feb 3 '11 at 5:41

You can do it easily with a nice one liner:

grep -l -i -r -Z pattern | xargs -0 -I source cp source /target

Some comments how it works. Grep's -l option prints just a file name if there is a match in the file, so it produces a list of files to be copied. Xargs command constructs a command for each copy command and executes it. Xargs replaces argument named "source" with a file name read from standard input. Spaces and other funny characters in file names are handled with -Z and -0 options.

share|improve this answer
+1 One small improvement: use ack (or ack-grep) instead of grep. Ack is a lot faster and supports perl regex. – mehaase Mar 4 '11 at 5:04
@mehaase: You're right, ack is really good for greping source files! – JooMing Mar 7 '11 at 21:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .