简体   繁体   中英

Bash: Find files containing a certain string and copy them into a folder

What I want: In a bash script: Find all files in current directory that contain a certain string "teststring" and cop them into a subfolder "./testfolder"

Found this to find the filenames which im looking for

find . -type f -print0 | xargs -0 grep -l "teststring"

..and this to copy found files to another folder (here selecting by strings in filename):

find . -type f -iname " stringinfilename " -exec cp {} ./testfolder/ \\;

Whats the best way to combine both commands to achieve what I described at the top?

Just let find do both:

find . -name subdir -prune -o -type f -exec \
    grep -q teststring "{}" \; -exec cp "{}" subdir \;  

Note that things like this are much easier if you don't try to add to the directory you're working in. In other words, write to a sibling dir instead of writing to a subdirectory. If you want to wind up with the data in a subdir, mv it when you're done. That way, you don't have to worry about the prune (ie, you don't have to worry about find descending into the subdir and attempting to duplicate the work).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM