LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   find files with pattern, then copy those files to another directory (http://www.linuxquestions.org/questions/programming-9/find-files-with-pattern-then-copy-those-files-to-another-directory-649129/)

ncsuapex 06-13-2008 03:07 PM

find files with pattern, then copy those files to another directory
 
I am trying to find files that match a certain pattern and then copy just those files to another directory.

So far I have this, which find the files that match my pattern but I can't figure out how to then copy those to another directory.

find . -type f -maxdepth 1 -name "*" -exec grep -l "pattern" {} \;


I have tried adding
find . -type f -maxdepth 1 -name "*" -exec grep -l "pattern" -exec cp /directory {} \;



but that fails.

I've also tried a script which fails:

#!/bin/bash
for i in find . -type f -maxdepth 1 -name "*" -exec grep -l "pattern" {} \;
do
cp $i directory
done



but all that does is copy ALL the files into the new directory







edit:


cheap and dirty way that I figured out:


#!/bin/bash
find . -type f -maxdepth 1 -name "*" -exec grep -l "pattern" {} \; >> filename

for b in `cat filename`
do
cp $b test
done

osor 06-13-2008 03:25 PM

Quote:

Originally Posted by ncsuapex (Post 3184024)
find . -type f -maxdepth 1 -name "*" -exec grep -l "pattern" {} \;


I have tried adding
find . -type f -maxdepth 1 -name "*" -exec grep -l "pattern" -exec cp /directory {} \;



but that fails.

Why are you passing the -l flag to grep? What you want is for grep to exit with success if the pattern is found and exit with failure if the pattern is not found. If a success is encountered, then the remaining arguments to find are processed. Also, your cp syntax is backwards.

Try something like this:
Code:

find . -maxdepth 1 -type f -exec grep -q "pattern" '{}' ';' -exec cp '{}' /path/to/destination ';'

ncsuapex 06-13-2008 03:48 PM

thanks

find . -maxdepth 1 -type f -exec grep -q "pattern" '{}' ';' -exec cp '{}' /path ';'


worked, I didn't know how to pass 2 exec expressions on one line.


I used the -l because I wanted just the filename not the matching lines

Ephracis 06-14-2008 07:32 AM

Why use grep in the first place?

find . -maxdepth 1 -type f -regex "pattern" -exec cp {} /directory \;

PradeepKr 08-13-2010 03:38 PM

How about using xargs? Something like this.


All times are GMT -5. The time now is 05:59 PM.