Sam
Sam

Reputation: 31

Grep and Copy - Bash Scripting

I'm trying to grep, copy, and rename the files copied in the destination. So, basically I want to look in a directory for a file that contains a certain string, and copy those files when I find a match using grep and rename them once copied. I've been reading a lot but I can't seem to figure it out. Here's my script

for file in $(grep -R 'myname' /searchdirectory)
do
cp -t $file /destinationfolder
done

This doesn't seem to work. Once I figure this out, then I need to figure out how to rename. Any assistance would be appreciated.

Upvotes: 0

Views: 1447

Answers (3)

blaucuk
blaucuk

Reputation: 165

Here is a 1-liner for you:

ls | grep 'pattern' | xargs -i cp {} /path/to/destination

Upvotes: 2

Sriharsha Kalluru
Sriharsha Kalluru

Reputation: 1823

Use grep -l instead of simple grep command.

You are using simple grep command and it lists both the filename as well as output. But if you use -l option then it lists only file names and then you can copy them in for loop.

for file in $(grep -l -R 'myname' /searchdirectory)
do
cp -t $file /destinationfolder
done

Upvotes: 0

kojiro
kojiro

Reputation: 77127

You have a few options. On most modern systems you can use xargs:

grep -l --null "$pattern" "$srcPath" |
    xargs -0 -I{} cp {} "$destPath"

On any POSIX compliant system you can use find:

find "$srcPath" -maxdepth 1 -type f -exec grep -q "$pattern" {} \; \
    -exec cp {} "$destPath" +

The two things wrong with your approach are:

  1. You need the -l flag to grep.
  2. You aren't accounting for whitespace and glob expansion on the command substitution, which could be a nightmare.

Upvotes: 1

Related Questions