2

tac unzipped.log | grep -m1 pattern works perfectly fine but I am not able to use the tac command on zipped files.

tac zipped.gz | zgrep -m1 pattern returns nothing.

Is there anyway to use tac without unzipping my file ?

  • why not directly use zgrep -m1 pattern zipped.gz? why to use tac? – harish.venkat May 29 '14 at 8:50
  • Because my log files are huge and the pattern i am looking forward to is located towards the end of file – Ramneek May 29 '14 at 9:54
5

gzip operates as a stream from the first byte to the last byte; you can't start decompressing in the middle. Most compression tools do that, because if you allow decompressing from the middle, then you aren't taking full advantage of similarities between the beginning and the end. So to search a string in a gzipped file, you need to decompress the whole file anyway (at least until the first match, if you're only interested in the first match).

In addition, tac would reverse the lines, not the bytes. Since a decompressed file isn't divided into lines (they are binary files, where a line break is a byte like any other), this would jumble the file into something unusable.

You can reverse the decompressed file:

zcat zipped.gz | tac | grep -m1 pattern 

However, this isn't necessarily faster than searching the whole file, because tac itself is not that fast (most applications read from the beginning to the end, so kernels tend to optimize that case, and then tac has to test every byte to see if it's a newline). If you only want the last line, you can then extract it:

zcat zipped.gz | grep pattern | tail -n1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.