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.
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.
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.
To copy multiple files you can use wildcards (cp *. extension) having same pattern. Syntax: cp *.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With