I'm looking for a way to display the filename when using this command:

cat *.tcp | grep "tcp" | grep "open" | sort | uniq

Is there a way to do it?


grep tcp *.tcp | grep open | sort -u

Giving multiple filenames to grep will, by default, cause grep to prefix the matching output lines with the filename(s) they matched in. The only other change I made was to combine sort | uniq into sort -u (and to remove the quotes that are unnecessary here).

  • 1
    +1 although I think it has the potential for false matches if any of the filenames matches the pattern open: maybe that's not an issue in this particular application - otherwise perhaps consider replacing the second grep by an awk e.g. awk -F: '$2 ~ /open/'? – steeldriver Jul 8 '15 at 17:41
  • fair point on the filename possibly matching, although the OP's question implied that filenames would become part of the pipeline regardless. The awk statement you have now wouldn't quite work; it's only matching against field 2, and would miss matches in fields 3 & on. – Jeff Schaller Jul 8 '15 at 18:04
grep  -H 'tcp'  

-H, --with-filename Print the file name for each match. This is the default when there is more than one file to search.

  • 2
    How would I incorporate this into my command and keep the formatting of the columns that my command gives me? – Proletariat Jul 8 '15 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.