Reputation: 55
I want to look through 100K+ text files from a directory and copy to another directory only the ones which contain at least one word from a list.
I tried doing an if statement with grep and cp but I have no idea how to make it to work this way.
for filename in *.txt
do
grep -o -i "cultiv" "protec" "agricult" $filename|wc -w
if [ wc -gt 0 ]
then cp $filename ~/desktop/filepath
fi
done
Obviously this does not work but I have no idea how to store the wc result and then compare it to 0 and only act on those files.
Upvotes: 0
Views: 94
Reputation: 781096
Use the -l
option to have grep
print all the filenames that match the pattern. Then use xargs
to pass these as arguments to cp
.
grep -l -E -i 'cultiv|protec|agricult' *.txt | xargs cp -t ~/desktop/filepath --
The -t
option is a GNU cp
extension, it allows you to put the destination directory first so that it will work with xargs
.
If you're using a version without that option, you need to use the -J
option to xargs
to substitute in the middle of the command.
grep -l -E -i 'cultiv|protec|agricult' *.txt | xargs -J {} cp -- {} ~/desktop/filepath
Upvotes: 3