This question already has an answer here:
grep -rl "KORD" ./
searches a directory and returns a list of files containing "KORD" in the file contents (not the title).
Users-MacBook-Air:myPhotorec user$ grep -rl "KORD" ./ .//output_apikey.txt .//recup_dir.17/f13470392.txt .//recup_dir.49/f45361992.txt .//recup_dir.49/f45362424.txt .//recup_dir.53/f48768408.txt .//recup_dir.53/f49295480.txt
Is there a preferred command(xargs?) that augment the grep command to print the output file list to the console and copy each file to the a directory: ./ORD ?
I suspect that there is more than one way to 'skin a cat': I am looking forward to seeing more than one solution
JOHN1024's XARGS Solution
The duplicate label prevents posting this modified posting as answer:
grep -rl --null --include '*.txt' KORD . | xargs -0r cp -t /path/to/dest
Because this command uses NUL-separation, it is safe for all file names including those with difficult names that include blanks, tabs, or even newlines.
The above requires GNU
cp. For BSD/OSX, try:
grep -rl --null --include '*.txt' KORD . | xargs -0 sh -c 'cp "$@" /path/to/dest' sh
How it works:
grepoptions and arguments
-rtells grep to search recursively through the directory structure. (On FreeBSD,
-rwill follow symlinks into directories. This is not true of either OS/X or recent versions of GNU
--include '*.txt'tells grep to only return files whose names match the glob
*.txt(including hidden ones like
-ltells grep to only return the names of matching files, not the match itself.
--nulltells grep to use NUL characters to separate the file names.
LINUX/UNIXtells grep to look only for files whose contents include the regex
.search in the current directory. You can omit it in recent versions of GNU
grep, but then you'd need to pass a
--option terminator to
cpto guard against file names that start with
xargsoptions and arguments
-0tells xargs to expect NUL-separated input.
-rtells xargs not to run the command unless at least one file was found. (This option is not needed on either BSD or OSX and is not compatible with OSX's
cp -t /path/to/destcopies the directories to the target directory. (