Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading