Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy files found with grep

Tags:

grep

bash

cp

pipe

I am running this command to find all my files that contain (with help of regex)"someStrings" in a tree directory.

grep -lir '^beginString' ./ -exec cp -r {} /home/user/DestinationFolder \; 

It found files like this:

FOLDER
a.txt
-->SUBFOLDER
  a.txt
---->SUBFOLDER
     a.txt

I want to copy all files and folder, with the same schema, to the destination folder, but i don't know how to do it. It's important copy files and folder, because several files found has the same name and I need to keep it.

like image 673
user6372336 Avatar asked May 23 '16 16:05

user6372336


People also ask

Can grep find files?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in.

Can you grep multiple files?

To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.

How do I copy multiple files in one command?

To copy multiple files you can use wildcards (cp *. extension) having same pattern. Syntax: cp *.


1 Answers

Try this:

find . -type f -exec grep -q '^beginString' {} \; -exec cp -t /home/user/DestinationFolder {} +

or

grep -lir '^beginString' . | xargs cp -t /home/user/DestinationFolder

But if you want to keep directory structure, you could:

grep -lir '^beginString' . | tar -T - -c | tar -xpC /home/user/DestinationFolder

or if like myself, you prefer to be sure about kind of file you store (only file, no symlinks), you could:

find . -type f -exec grep -l '^beginString' {} + | tar -T - -c |
    tar -xpC /home/user/DestinationFolder

and if your files names could countain spaces and/or special characters, use null terminated strings for passing grep -l output (arg -Z) to tar -T (arg --null -T):

find . -type f -exec grep -lZ '^beginString' {} + | tar --null  -T - -c |
    tar -xpC /home/user/DestinationFolder
like image 130
F. Hauri Avatar answered Sep 22 '22 07:09

F. Hauri