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 ?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
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).
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