2

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?

0

2 Answers 2

10

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

2
  • 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/'? Commented Jul 8, 2015 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. Commented Jul 8, 2015 at 18:04
0
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.

1
  • 2
    How would I incorporate this into my command and keep the formatting of the columns that my command gives me? Commented Jul 8, 2015 at 16:24

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.