2

Suppose I have two tar.gz files

a1.tar.gz
a2.tar.gz

and each archive contains many files, including a file called

target.txt

How do I search for BLAH in target.txt in both of these archives using zgrep without searching all of the other files in each archive?

If I try

zgrep -a BLAH *.tar.gz

then that searches all files in each archive, and if I try

zgrep --include=target.txt -a BLAH *.tar.gz

then I get

zgrep: --include=target.txt: option not supported
Graeme Moss
  • 7,995
  • 4
  • 29
  • 42
  • 1
    as per manual, `These grep options will cause zgrep to terminate with an error code: (-[drRzZ]|--di*|--exc*|--inc*|--rec*|--nu*)` which explains the error you got.. not sure if there's an easy way around this, but may be use https://unix.stackexchange.com/questions/61461/how-to-extract-specific-files-from-tar-gz to first extract only `target.txt` from these archives and then use normal grep... – Sundeep Jul 29 '19 at 15:10

1 Answers1

1

You can use zgrep, however this command will not locate the file you are looking for as it searches the entire tar-formatted file for matches. This will report which tar file has a match for BLAH but this does not limit searching tar files containing the file target.txt.

There is an open source tool called ugrep to search archives (zip, tar, pax, cpio, jar) and tar.gz tarballs. Use option -z and -g target.txt to search for BLAH in target.txt in all of the tar files found recursively:

ugrep -z "BLAH" -g target.txt

To search the working directory only without recursing deeper:

ugrep -z "BLAH" -g target.txt .

Note that option -g takes a glob. Use a quoted glob like -g "*.txt" to match all .txt files.

Dr. Alex RE
  • 1,772
  • 1
  • 15
  • 23