Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

2 Answers

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.

e.g.

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

    if [ "$?" -eq 0 ]
    then
            cp "$i" mvd
    fi
done
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
1  
if grep -inqs 'Power' "$i"; then –  grawity Feb 3 '11 at 5:41
show 2 more comments

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  
+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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.