I have a file as belowFHEADTHEADTCUSTTITEMTTENDTTAILTHEADTCUSTTCUSTTITEMTITEMTTENDTTAILTHEADTCUSTTITEMTTENDTTAILTHEADTCUSTTCUSTTITEMTTENDTTAILI need to count thr  number of occurrence of ONLY TCUST records between THEAD and TTAIL where the occurrence is more than once and print that file name and line.There will be multiple files so I need to print the filename as well.Expected result is           THEADTCUSTTCUSTTITEMTITEMTTENDTTAILTHEADTCUSTTCUSTTITEMTTENDTTAIL    name of file
count number of words between 2 fixed words
text processing
$ awk '  /THEAD/{f=1; c=0; a = $0; next}  f{a = a ORS $0; if(/TCUST/) c++}  /TTAIL/{f=0; if(c > 1){print a; m=1} }  ENDFILE{if(m) print FILENAME; m=0}  ' ip.txtTHEADTCUSTTCUSTTITEMTITEMTTENDTTAILTHEADTCUSTTCUSTTITEMTTENDTTAILip.txt/THEAD/{f=1; c=0; a = $0; next} starting pattern, set flag and initialize counter. Save current line for later printingf{a = a ORS $0; if(/TCUST/) c++} when flag is set, accumulate input lines in a variable and increment counter if line matches TCUST/TTAIL/{f=0; if(c > 1){print a; m=1} } ending pattern, clear flag. Print contents of a if counter is greater than 1, also set variable m that at least one match is foundENDFILE{if(m) print FILENAME; m=0} after all lines are processed for a file, print input file name if m is set and clear before next file is processed (Thanks @Costas for pointing out multiple file requirement)Note: ENDFILE is GNU awk specific, I am not sure how to handle it without ENDFILEThanks @Costas for solution not dependent on GNU specificENDFILE:$ awk '  FNR==1{if(m) print fname; m=0; fname=FILENAME}  /THEAD/{f=1; c=0; a = $0; next}  f{a = a ORS $0; if(/TCUST/) c++}  /TTAIL/{f=0; if(c > 1){print a; m=1} }  END{if(m) print fname}  ' *.txt