Searching for a string that contains the file name

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).


It is needed to grep each file found.

-l instructs grep to print the filename only when the regex is found.

If the filenames does not contain any / char, give a try to this:

find a_directory -type f -name \*.py.txt -exec sh -c '
  for fname; do
    basename="${fname##*/}"
    grep -lF "@code prefix.${basename%.*}" "${fname}"
  done' sh {} +

see man bash for the items below:

  • "${fname##*/}" is file1.py.txt, if fname == a_directory/file1.py.txt
  • "${basename%.*}" is file1.py, if basename == file1.py.txt