To avoid creating temporary files, you can use GNU tar's --to-stdout
option.
The code below is careful about spaces and other characters in paths that may confuse the shell:
#! /usr/bin/perl
use warnings;
use strict;
sub usage { "Usage: $0 pattern tar-gz-file ..\n" }
sub output_from {
my($cmd,@args) = @_;
my $pid = open my $fh, "-|";
warn("$0: fork: $!"), return unless defined $pid;
if ($pid) {
my @lines = <$fh>;
close $fh or warn "$0: $cmd @args exited " . ($? >> 8);
wantarray ? @lines : join "" => @lines;
}
else {
exec $cmd, @args or die "$0: exec $cmd @args: $!\n";
}
}
die usage unless @ARGV >= 2;
my $pattern = shift;
foreach my $tgz (@ARGV) {
chomp(my @toc = output_from "tar", "-ztf", $tgz);
foreach my $tlg (grep /\.tlg\z/, @toc) {
my $line = 0;
for (output_from "tar", "--to-stdout", "-zxf", $tgz, $tlg) {
++$line;
print "$tlg:$line: $_" if /$pattern/o;
}
}
}
Sample runs:
$ ./grep-tlgs hello tlgs.tar.gz
tlgs/another.tlg:2: hello
tlgs/file1.tlg:2: hello
tlgs/file1.tlg:3: hello
tlgs/third.tlg:1: hello
$ ./grep-tlgs ^ tlgs.tar.gz
tlgs/another.tlg:1: blah blah
tlgs/another.tlg:2: hello
tlgs/another.tlg:3: howdy
tlgs/file1.tlg:1: whoah
tlgs/file1.tlg:2: hello
tlgs/file1.tlg:3: hello
tlgs/file1.tlg:4: good-bye
tlgs/third.tlg:1: hello
tlgs/third.tlg:2: howdy
$ ./grep-tlgs ^ xtlgs.tar.gz
tar: xtlgs.tar.gz: Cannot open: No such file or directory
tar: Error is not recoverable: exiting now
tar: Child returned status 2
tar: Exiting with failure status due to previous errors
./grep-tlgs: tar -ztf xtlgs.tar.gz exited 2 at ./grep-tlgs line 14.