Bash – How to grep inside a specific file in tar.gz without extracting

bashgreptar

I'm looking for a command that can perform a grep operation in a specific file contained in a tar.gz archive.

Example:

file: archive.tar.gz, which ​contains:

fileA.txt
fileB.txt
fileC.txt

I want to grep only inside fileA.txt, not in the other two, without extract the files from the original archive, with only one command.

Is it possible?

I have tried:

for f in /path/*.gz; do
    tar -xzf "$f" --to-command='grep -Hn --label="$TAR_ARCHIVE/$TAR_FILENAME" pattern || true'
done

This command performs the grep in all files included in the archive, but this is not exactly what I need. I need a command that greps only in the file I want to search in.

Best Answer

Tell tar which file it should process inside the archive:

for f in /path/*.gz; do
  tar -xzf "$f" --to-command='grep -Hn --label="$TAR_ARCHIVE/$TAR_FILENAME" pattern || true' fileA.txt
done

(fileA.txt at the end of the tar command).

Related Question