ImLearning
ImLearning

Reputation: 200

How put every files result by a grep into a zip file

I'm searching every txt files that contains string1 and string2

grep -rnE --include='*.txt' 'string1|string2'

Now I want to put all those files into a zip file.

Thanks

EDIT this script suggest by @anubhava works for me

grep --null -rlE --include='*.txt' 'string1|string2' | xargs -0 -I {} zip test.zip '{}'

Upvotes: 2

Views: 1200

Answers (2)

anubhava
anubhava

Reputation: 785108

You can use -l option in grep to output only filename and pipe it to xargs to create zip for each found fine:

grep --null -rlE --include='*.txt' 'string1|string2' |
xargs -0 -I {} zip '{}'.zip '{}'

Note use of --null option with -0 in xargs to address filenames with whitespaces, special characters.


To create a single zip file containing each matched file use:

grep --null -rlE --include='*.txt' 'string1|string2' |
xargs -0 zip test.zip

Upvotes: 2

Vijayendar Gururaja
Vijayendar Gururaja

Reputation: 860

since you wanted files that contain both string1 and string2

$ files=""; for i in *.txt; do if  grep -q string1 $i &&  grep -q string2 $i; then files="$files $i"; fi; done
$ zip files.zip ${files}

cleaner version

files=""; 
for i in *.txt; 
  do 
    if  grep -q string1 $i &&  grep -q string2 $i; then 
      files="$files $i"; 
    fi; 
  done
zip files.zip ${files}

DEMO:

$ cat SO/file1.txt
there is string1
there is also string2
$
$ cat SO/file2.txt
there is just string1
$
$ cat SO/file3.txt
here we have both string1 and string2
$
$
$ files="";
$ for i in SO/*.txt;
>   do
>     if  grep -q string1 $i &&  grep -q string2 $i; then
>       files="$files $i";
>     fi;
>   done
$ zip files.zip ${files}
  adding: SO/file1.txt (deflated 26%)
  adding: SO/file3.txt (deflated 11%)
$

Upvotes: 1

Related Questions