Searching for a Specific String in multiple files and Copying all the files recursively

StackOverflow https://stackoverflow.com/questions/23284440

  •  09-07-2023
  •  | 
  •  

Question

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
Was it helpful?

Solution

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.

OTHER TIPS

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/
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top