How to zip a list of files in Linux

I have many files I need to zip into a single directory. I don't want to zip all the files in the directory, but only ones matching a certain query.

I did

grep abc file-* > out.txt 

to make a file with all the instances of "abc" in each file. I need the files themselves. How can I tell bash to zip only those files?

3

2 Answers

Very simple:

zip archive -@ < out.txt

That is, if your out.txt file contains one filename per line. It will add all the files from out.txt to one archive called archive.zip.

The -@ option makes zip read from STDIN.

If you want to skip creating a temporary out.txt file, you can use grep's capability to print filenames, too. -r enables recursive search (might not be necessary in your case) and -l prints only filenames:

grep -rl "abc" file-* | zip archive -@
5

Alternatives to the accepted answer, from here:

cat out.txt | zip -@ zipfile.zip
cat out.txt | zip -@ - > zipfile.zip
zip zipfile.zip $(cat out.txt) -r
zip zipfile.zip -r . 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like