Search files for a string and if found check if a file with paired name exists in the same directory

findgrepls

I have many different files with the same ending .ft1 that may or may not contain one specific word special. For the files that contain this word, I want to check whether another file with a different ending .log exists in that directory.

What I got so far is this:

find . -name "*.ft1" -exec grep -l "special" {} \; -execdir ls *log \;

However, this gives me an error each time the ls is executed:

ls: cannot access *log: No such file or directory

But I know that there are such files in that directory. I also tried escaping the star, so the expression becomes -execdir ls \*log \;, but the error persists.

I also had a look at this similar question, but I cannot currently see how that helps me with my problem.

How do I get this to behave correctly? Bonus points for a solution that only lists .log files with the same name stem as the found .ft1 files.

Best Answer

Your issue is that you need a shell to interpret the *.log glob. So you need -execdir to invoke a shell. The following snippet will also address your "same name stem" requirement

find . -name "*.ft1" -exec grep -l "special" {} \; \
-execdir bash -c 'x=$1; x=${x%.txt}; ls "$x".log' bash {} \;