I am interested in recursively grepping for a string in a directory for a pattern and then cp'ing the matching file to a destination directory. I thought I could do something like the following, but it doesn't seem to make sense with linux's find tool:
find . -type f -exec grep -ilR "MY PATTERN" | xargs cp /dest/dir
Is there a better way of going about this? Or a way that even works would be a solid start.
Do
man xargs
and look at the-I
flag.Also,
find
expects a\;
or+
after the-exec
flag.xargs
reads its standard input and puts them at the end of the command to be executed. As you've written it, you would end up executingwhich is backwards from what you want.
You could use the
-I
option to specify a placeholder forxargs
, like this:xargs -I '{}' cp '{}' /dest/dir
.Also,
find
takes care of the recursion, so yourgrep
does not need-R
.Final solution:
I don't think you need find. Recursive grep:
None of the examples above takes into account the possibility of
grep
's-l
generating duplicated results (files with the same name, but in different places), and thereforefind
'sexec
's hook overwriting files in the destination directory.An attempt to solve this: