Issue
I need a way to tell if grep does find something, and ideally pass that return value to an if statement.
Let's say I have a tmp
folder (current folder), in that there are several files and sub-folders. I want to search all files named abc
for a pattern xyz
. The search is assumed to be successful if it finds any occurrence of xyz
(it does not matter how many times xyz
is found). The search fails if no occurrence of xyz
is found.
In bash, it can be done like this:
find . -name "abc" -exec grep "xyz" {} \;
That would show if xyz
is found at all. But I'm not sure how pass the result (successful or not) back to an if
statement.
Any help would be appreciated.
Solution
You can try
x=`find . -name abc | xargs grep xyz`
echo $x
Or, to properly handle whitespaces and endlines in filenames:
x=`find . -name abc -print0 | xargs -0 grep xyz`
echo $x
That is, x contains your return value. It is blank when there is no match.
Answered By - Alain Answer Checked By - Clifford M. (WPSolving Volunteer)