November 2nd, 2012, 01:47 PM
How to grep from multiple files given one of those files dont exist
I am trying to grep for a particular word from two files like below. I need to find the word in one of the two files
grep "myWord" file1 file2 && echo 1 or echo 0
The issue is that I have to search in both the files, but sometimes one of these files doesnt exist. So even when the word is present in one of the files it still returns a 0.
I know there are different wyas where I can split up this one line and do the same thing, but just wanted to see if there is something that I can do grep it in the same single line
November 2nd, 2012, 02:45 PM
This does not seem to be a Perl question. Or is it?
The obvious answer, though, is to check for the existence of your files beforehand.
November 2nd, 2012, 03:04 PM
This is not a Perl question but I did not find a section for Unix shell script related questions. Sorry about that. I was thinking I could use some OR(||) command to grep from either of the two files without causing it to fail. Or mebbe I have to do it like below instead of trying it to do in one line
egrep word file1 || egrep word file2 && echo yes || echo no
November 2nd, 2012, 05:40 PM
If you still wanted to do it on one line, This is a simple example in bash:
if [[ -s "file1" ]]; then grep word file1; fi; if [[ -s "file2" ]]; then grep word file2; fi