Reputation: 929
I am having 35K + odd files in multiple directories and subdirectories. There are 1000 odd files (.c .h and other file names) with a unique string "FOO" in the FILE CONTENT. I am trying to copy those files alone (with the directory structure preserved) to a different directory 'MEOW'. Can some one look in to my bash execution and correct my mistake
for Eachfile in `find . -iname "*FOO*" `
do
cp $Eachfile MEOW
done
getting the following error
./baash.sh: line 2: syntax error near unexpected token `$'do\r''
'/baash.sh: line 2: `do
Upvotes: 1
Views: 146
Reputation: 2160
In case you only want to search for the string FOO in .c and .h file then
find ./ -name "*\.c" -o -name "*\.h" -exec grep -l FOO {} \; | xargs cp -t MEOW/
For me its working even without --null
option to xrags
, if doesn't for you.. then append -0
in xargs part as follow:
xargs -0 cp -t MEOW/
Upvotes: 1
Reputation: 113994
To find all files under the current directory with the string "FOO" in them and copy them to directory MEOW
, use:
grep --null -lr FOO . | xargs -0 cp -t MEOW
Unlike find
, grep
looks in the contents of a file. The -l
option to grep
tells it to list file names only. The -r
option tells it to look recursively in subdirectories. Because file names can have spaces and other odd characters in them, we give the --null
option to grep
so that, in the list it produces, the file names are safely separated by null characters. xargs -0
reads from that list of null-separated file names and provides them as argument to the command cp -t MEOW
which copies them to the target directory MEOW
.
Upvotes: 1
Reputation: 98118
for file in $(find -name '*.c' -o -name '*.h' -exec grep -l 'FOO' {} \;); do
dname=$(dirname "$file")
dest="MEOW/$dname"
mkdir -p $dest
cp "$file" "$dest"
done
Upvotes: 0