Sai Sai - 5 months ago 17
Bash Question

Is there way to use If condition inside a find command with option exec?

scenario: There are multiple files in an folder, I'm trying to find specific set of files and if a given file has specific info then I need to grep the information.


find /abc/test \( -type f -name 'tst*.txt' -mtime -1 \) -exec grep -Po '(?<type1).*(?=type1|(?<=type2).*(?=type2)' {} \;

I need to include if condition along with find -exec (if grep is true then print the above)

if grep -q 'case=1' <filename>; then
grep -Po '(?<type1).*(?=type1|(?<=type2).*(?=type2)'



You can use -exec in find as a condition -- the file matches if the command returns a successful exit code. So you can write:

find /abc/test -type f -name 'tst*.txt' -mtime -1 -exec grep -q 'case=1' {} \; -exec grep -Po '(?<type1).*(?=type1|(?<=type2).*(?=type2)' {} \;

Tests in find are evaluated left-to-right, so the second grep will only be executed if the first one was successful.

If your conditions are more complicated, you can put the whole shell code into a script, and execute the script with -exec. E.g. put this in

if grep -q 'case=1' "$1"; then
    grep -Po '(?<type1).*(?=type1|(?<=type2).*(?=type2)' "$1";

and then do:

find /abc/test -type f -name 'tst*.txt' -mtime -1 -exec ./ {} \;