Help with unix tar and grep loop

I need help creating a loop that will take one of my .tar.gz file extensions, unzip it and find the files inside (with the .tlg extension) using grep -a โ†’ output.text.

In outout.text, I will need the appropriate data, as well as the name of the file and the parent tar that it came from

this search was performed alone, I would like to delete unused files, and preocess continue in the next tar file until all traces are checked.

I canโ€™t deploy everything on one, because I donโ€™t have disk space for this

Can anybody help

thank

+3
source share
2 answers

, GNU tar --to-stdout.

, :

#! /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;
    }
  }
}

:

$ ./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.
0

, , ; - :

match="somestring"
mkdir out/
for i in *.tar.gz; do
 mkdir out/${i} # create outdir
 tar -C out/${i} -xf ${i} # extract to sub-dir with same name as tar; 
                          # this will show up in grep output
 cd out
 grep -r ${match} ${i} >> ../output.text
 cd ..
 rm -rf out/${i} # delete untarred files
done

, $i rm -rf .

0

Source: https://habr.com/ru/post/1753692/


All Articles