Searching for a string that contains the file name

file searchgrepsearchtext processing

I have a large set of files in a directory. The files contains arbitrary text.

I want to search for the file name inside that particular file text. To clarify, I have file1.py.txt (yeas, two dots .py.txt) and file2.py.txt both contains texts. I want to search for the existence of the string @code prefix.file1.py inside file1.py.txt and for the string @code prefix.file2.py inside file2.py.txt

How can I customize grep such that it goes through every file in the directory, search for the string in each file using that particular file name?

EDIT:

The output I am looking for is written in a separate file, result.txt which contains:
filename (if a match is found), the line text (where the match is found)

Best Answer

With GNU awk:

gawk '
  BEGINFILE{search = "@code prefix." substr(FILENAME, 3, length(FILENAME) - 6)}
  index($0, search)' ./*.py.txt

Would report the matching lines.

To print the file name and matching line, change index($0, search) to

  index($0, search) {print FILENAME": "$0}

Or to print the file name only:

  index($0, search) {print FILENAME; nextfile}

Replace FILENAME with substr(FILENAME, 3) to skip outputting the ./ prefix.

The list of files is lexically sorted. The ones whose name starts with . are ignored (some shells have a dotglob option to add them back; with zsh, you can also use the (D) glob qualifier).

Related Question