Unix script to search in a compressed .gz file

I want to get some lines from a file that is in a compressed .gz file.

The .gz file contains many txt files, and I want to find a line in all these txt files and should get the previous 3-line line, including the current line (where the search line is present).

I tried zgrepand got the line number, but when I use the heador command tail, it gives some garbage values. I think that we can not use a command heador taila compressed file containing multiple files.

Please suggest if there is an easy way?

+3
source share
2 answers

, , - tarball , - . , -O, .

tar -tzf file.tar.gz | grep '\.txt' | xargs tar -Oxzf file.tar.gz | grep -B 3 "string-or-regex" .tar.gz , ".txt", grep , 3 . , tarball - , " " .

:

for file in $(tar -tzf file.tar.gz | grep '\.txt'); do 
    tar -Oxzf file.tar.gz "$file" | grep -B 3 --label="$file" -H "string-or-regex"
done

, .

(-z tar gzip. -t . -x extracts. -O , . tar -O -z, -: , tar tz file.tar.gz)

, grep. awk!

#!/usr/bin/awk -f
BEGIN { context=3; }
{ add_buffer($0) }
/pattern/ { print_buffer() }
function add_buffer(line)
{
    buffer[NR % context]=line
}
function print_buffer()
{
    for(i = max(1, NR-context+1); i <= NR; i++) {
        print buffer[i % context]
    }
}
function max(a,b)
{
    if (a > b) { return a } else { return b }
}

, grep -B, , , , 3 .

+5

gzip tar ? - .

0

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


All Articles