Quote:
Originally Posted by mddesai
Try this:
Code:
#!/bin/bash
for file in $(find . -type f -exec grep -l "19201020320" '{}' +)
do
cp $file /tmp
done
|
No, please
Don't Read Lines With For! The output of commands should always be processed with a
while+read loop, or some other similar technique that allows you to safely delimit the input with
null separators.
Always remember to quote your variables too, for similar reasons.
Code:
#!/bin/bash
while IFS='' read -d '' -r fname; do
cp "$fname" /tmp
done < <( find . -type f -exec grep -lZ "19201020320" '{}' + )
In this particular case, since it's
grep doing the actual printing, we need to use its
-Z option for null separators, rather than the usual
-print0 of
find.
Of course we can also use
xargs instead of the loop, since it can handle null separated input too.
Code:
find . -type f -exec grep -lZ '19201020320' '{}' + | xargs -0 cp -t /tmp
And actually,
find can probably be eliminated as well, since
grep can do recursive searching all by itself.
Code:
grep -lZR '19201020320' . | xargs -0 cp -t /tmp
You can also add
--include and
--exclude options for more exact file filtering if needed. See the man/info pages.
Finally, notice how I used the
-t option in
cp, to invert the order of the arguments and make the command simpler. I believe this is only available in
gnu cp, however.
PS: Please use ***
[code][/code]*** tags around your code and data, to preserve the original formatting and to improve readability. Do
not use quote tags, bolding, colors, "start/end" lines, or other creative techniques. Thanks.