Home > Mobile >  How to find filename in file content with bash script?
How to find filename in file content with bash script?

Time:04-11

I wrote this command in my shell but it's not doing what I wanted and I can't figure out what I did wrong. I want to get files from current directories which include their names in their content.

find -type f -exec grep -il {}  

I understand find -type f gives me standard files from the directory and -exec executes following grep command with pattern - which is filename - on given file (' '). Am I right? Because it seems like I don't understand something since it's not finding my file specially created for this purpose.

CodePudding user response:

on given file (' ')

executes the command on all found files. The {} is replaced by the list of files in current directory.

Debug with -exec echo grep -il {} .

You want:

-exec grep -Fil {} {} ';'

To search the filename {} as a pattern in the file named {}. The ';' terminates the command.

I also added -F to interpret pattern literally.

CodePudding user response:

File in current directory test.txt

Content of file includes "test"

find . -name 'test.txt' -exec grep -i 'test' {} \;

  • Related