7

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.

2
  • 1
    It's worth noting that tar.gz files don't offer random access, so accessing a file in the middle of a tar.gz necessarily involves decompressing all preceding files.
    – plugwash
    Apr 17, 2021 at 2:51
  • essentially a duplicate of this grep from tar.gz without extracting [faster one]. Too bad zgrep doesn't receive a file name
    – phuclv
    Apr 17, 2021 at 11:34

3 Answers 3

17

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).

0
3

You can restrict the files that should be extracted by tar.

Assuming you use GNU tar, use the --to-stdout option. It is easier then passing a correctly quoted command.

for TAR_ARCHIVE in /path/*.gz; do
  TAR_FILENAME="fileA.txt"
  tar -xzf "$TAR_ARCHIVE" --to-stdout "$TAR_FILENAME" | grep -Hn --label="$TAR_ARCHIVE/$TAR_FILENAME" pattern
done
2
  • 3
    $TAR_ARCHIVE and $TAR_FILENAME are magic envvars tar sets with --to-command. With --to-stdout, you need to fill them in manually
    – ilkkachu
    Apr 16, 2021 at 16:22
  • 1
    If you're doing this because it's easier to type interactively, presumably you'd just leave out the --label part, or at least simplify it to just the tar file name. Apr 17, 2021 at 20:40
0

ugrep searches tar.gz files with option -z.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .