问题
At times I have come across a situation whereby I have to copy all the files containing a specific pattern in its content from a folder to another.
For example, DirA
contains 100 files, out of which there are 60 files which contains a pattern FOO
. My requirement is to copy these 60 files from DirA
to DirB
.
I typically write a small shell script to do this job and it works properly. However, I am trying to understand if there is a way to it only using a combination of some commands such that I need not write any shell script.
回答1:
You can use
cp `grep -l 'FOO' dirA/*` dirB/
grep -l
will only output the name of the files matching the pattern.
回答2:
Copying files containing specific content and preserving directory structure can be done by:
cp --parents `grep -lr 'text_content' ./*` /path/to/copy/
回答3:
Following script will work what you are looking for
cd /"path were file exist"
grep -w "word you want to search inside a file" "file.name/write nothing in case multiple files" >/dev/null
if [ $? -eq 0 ]
then
mv ls -ltr | grep your word /path to move on
fi
回答4:
If all your required files start with FOO
cp dirA/FOO* dirB
来源:https://stackoverflow.com/questions/18450742/copying-files-containing-specific-text-in-its-content-from-a-folder-to-other