Basename in subshell

Hi All,

I would like to improve my bash scripting skill and found a problem which I do not understand. Task is to search and print files in directory (and subdirecories) which contains its own name. Files can have spaces in name.

This one works fine for files in main directory, but not for files placed in subdirectories:

find . -type f -exec sh -c "echo {} | sed s/'\.\/'/''/g" \; | xargs -I'{}' grep -H {} {} | cut -f1 -d:

So I tried to add basename in subshell and it is not working as I expected. There is no result. Path is printed like before.

[ok@x60 test]$ find . -type f -exec sh -c "echo {} | sed s/'\.\/'/''/g" \; | xargs -I'{}' echo grep -H `basename {}` "{}"
grep -H olooo olooo
grep -H 1 ib_iser 1 ib_iser
grep -H ala ma/00.00 kintegrityd ala ma/00.00 kintegrityd

When I changed basename to dirname to check what happens, I got:

[ok@x60 test]$ find . -type f -exec sh -c "echo {} | sed s/'\.\/'/''/g" \; | xargs -I'{}' echo grep -H `dirname {}` "{}"
grep -H . olooo
grep -H . 1 ib_iser
grep -H . ala ma/00.00 kintegrityd

So, why basename and dirname act like this? Thank you for any help on this :b:

If I understand what you are trying to do, this is the way I would have approached it:

find . -type f| while read f
do
    grep -l "${f##*/}" "$f"
done

Searches all regular files in all directories in and below the current directory and prints files whose contents contain the filename. Should work with file names that have spaces.

Thank you for reply. I think your solution is best possible :wink: But I have been thinking how to resolve this matter without for or while loop. Only for test purposes. This task is not so important. I'm just curious :wink:

I don't see a way, because the string being grepped for really is constantly changing. You could do so inside awk I suppose, but it would just mean moving the while loop inside awk instead of the shell.

It may look strange, but I believe that everything works :wink:

find . -type f -print | awk -F'/' '{print "grep -H \"" $NF "\" \"" $0 "\""}'  | bash | cut -f1 -d:

Corona688: thank you for tip about awk.