i need to grep on a group of files (some zipped, some not) for a particular pattern. I know zgrep can be used to grep on zipped files, but the script that is being run relies on return codes with different logic for return codes 0, 1, and anything else.
grep states: the exit status is 0 if selected lines are found and 1 otherwise. 2 if an error occurred.
zgrep states it works the same as grep, but can handle zipped files.
however with 2 files:
#test1
hello
and
#test2
goodbye
both in the same directory
grep "hello" * returns 0 as expected because the pattern is found in test1
zgrep "hello" * however returns 1 even though the pattern was found in test1. it returns 1 because the pattern was not found in test2. turns out if any file does not match the pattern, 1 is returned, even if all other files do match the pattern.
for my case, i only care if at least 1 files matches or if no files match. if some do and some don't, that should count as a success.
so is there any way i can grep on both zipped and unzipped files without zgrep and get proper return codes since zgrep seems bugged?
grep version: 2.20
zgrep version: 1.5
note: there is no way for me or even a system admin to change these version numbers without a months long approval process, so please avoid solutions like "update your stuff"
This seems to be a bug in zgrep. Try xzgrep.
$ xzgrep -q hello *; echo $?
0
$ zgrep -q hello *;echo $?
1
$ grep -q hello *;echo $?
0
You can also use zcat and grep together, if files are always gzipped.
$ zcat * | grep -q hello; echo $?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With