user1588737
user1588737

Reputation: 320

Copying files containing specific text in its content from a folder to other

At times I have come across a situation whereby I have to copy all the files containing a specific pattern in its content from a folder to another.

For example, DirA contains 100 files, out of which there are 60 files which contains a pattern FOO. My requirement is to copy these 60 files from DirA to DirB.

I typically write a small shell script to do this job and it works properly. However, I am trying to understand if there is a way to it only using a combination of some commands such that I need not write any shell script.

Upvotes: 4

Views: 6753

Answers (4)

Manoj Shekhawat
Manoj Shekhawat

Reputation: 449

Copying files containing specific content and preserving directory structure can be done by:

cp --parents `grep -lr 'text_content' ./*` /path/to/copy/

Upvotes: 1

sr01853
sr01853

Reputation: 6121

If all your required files start with FOO

cp dirA/FOO* dirB

Upvotes: 0

user2197712
user2197712

Reputation: 267

Following script will work what you are looking for

cd /"path were file exist"
grep -w "word you want to search inside a file" "file.name/write nothing in case    multiple files" >/dev/null

if [ $? -eq 0 ]

then
     mv ls -ltr | grep your word /path to move on 

     fi

Upvotes: 0

tomahh
tomahh

Reputation: 13661

You can use

cp `grep -l 'FOO' dirA/*` dirB/

grep -l will only output the name of the files matching the pattern.

Upvotes: 10

Related Questions