Search code examples
linuxgrepzip

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 '{}'

Solution

  • 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