0

I'm using grep -ril to be able to see all files that contain a certain string:

[user@machine]$ grep -ril "test string"
file1.log
file2.log
file3.log
file4.log
...

I then would like to zip all of the files that have been returned by that command. Is this possible?

I've tried things such as grep -ril myPattern | zip files.zip and grep -ril myPattern | zip > files.zip but nothing has worked so far.

Is there a workaround to this?

Thank you.

Ress
  • 25
  • 1
  • 5

2 Answers2

2

Use the zip command line switch -@ to have zip take the list of input files from standard input instead of from the command line. For example,

grep -ril "test string" | zip name-of-new-zip-file -@ 
Bob
  • 5,335
  • 5
  • 24
0

You can try the command on this way:

zip zipfile.zip `grep -ril "test string"`
Romeo Ninov
  • 3,195
  • 2
  • 13
  • 16
  • This suffers from the usual "any file with a space or starting with a dash" issue that makes it non generic, non stable and a generally bad habit to have as it can cause security issues in some cases. – Ginnungagap Nov 21 '21 at 08:16
  • @Ginnungagap, IMHO same for the answer of Bob – Romeo Ninov Nov 21 '21 at 09:57
  • It probably suffers from newlines in filenames but it doesn't suffer from a file called `-o` (for example) being interpreted as a command line switch by `zip` nor does it suffer from `filename with space` (again, for example) being interpreted as 3 separate files. And as a general rule, it's better to pipe than to expand on the command line since it's unlikely to change the behavior of the invoked program. – Ginnungagap Nov 22 '21 at 07:48
  • Actually, looking for an document illustrating this, I stumbled upon [this](https://insinuator.net/2014/12/revisiting-an-old-friend-shell-globbing/) which explains the issue and actually lists `zip` as a security issue with this kind of invocation. – Ginnungagap Nov 22 '21 at 07:50