How to zip a list of files in Linux

18

8

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?

john mangual

Posted 2014-11-02T14:04:12.793

Reputation: 315

Wildcards does not work? Why? If I can ask... – jherran – 2014-11-02T15:15:16.977

@jherran I don't want to zip all the files in the directory, 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. – john mangual – 2014-11-02T15:18:49.750

What @jherran means is zip ZipFile.zip file-*, which is the obvious way to do it. You would need an intermediate file only if you were using a complex find or a concatenation of file lists from different searches. – AFH – 2014-11-02T18:07:44.587

Answers

32

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 -@

slhck

Posted 2014-11-02T14:04:12.793

Reputation: 182 472

Works nicely, except I have a list file where there are spaces in file names. I tried both escaping them with \ and not escaping them, once in quotes and once without quotes around the file name (one line - one file name). Nothing worked so far. – Thomas W. – 2015-12-16T07:03:56.047

2I made it work with \ escaped spaces and no quotes in the file and the following: cat out.txt | while read line ; do xargs zip archive.zip $line ; done – Thomas W. – 2015-12-16T07:50:50.907

if you want to zip files with similar names you could try zip archive.zip $(ls common_name*) – chepe263 – 2017-02-09T17:08:20.277

@chepe263 This breaks if files have spaces in their path. It's generally discouraged to parse ls output. – slhck – 2017-02-10T07:45:47.853

For anyone else on a mac who wound up here courtesy of search engine indexing, the -@ option syntax works fine as of 10.16, even though the man page still includes language about not on MacOS – Aidan Miles – 2020-02-10T19:48:57.553

0

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 . -i@out.txt

sancho.s Reinstate Monica

Posted 2014-11-02T14:04:12.793

Reputation: 2 404