'How to find filename in file content with bash script?
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.
Solution 1:[1]
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.
Solution 2:[2]
File in current directory test.txt
Content of file includes "test"
find . -name 'test.txt' -exec grep -i 'test' {} \;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KamilCuk |
| Solution 2 | h1w |
