0

I am running cygwin, grep 2.21 on Windows 7.
I am trying to get all tcp connections from netstat, so I run the following:

netstat | grep -i "^(TCP|UDP)"

Now, it returns nothing, but when I run netstat it clearly returns a bunch of tcp connections. I also tried :

netstat | egrep -i "^(TCP|UDP)"

Also returns nothing. What am I missing here? I thought that the caret means "begins with". Thanks.

4
  • The caret matches the position before the first character in a string. Is TCP or UDP the first part of a string (is there any whitespace before it)?
    – jmrah
    Commented Jun 26, 2015 at 0:20
  • My guess is it's something to do with netstat being a dynamic utility - there's no output available to pipe into grep. Even if you do netstat | grep "80" it doesn't work. Commented Jun 26, 2015 at 0:23
  • @remus What do you mean by "dynamic utility"? If it displays output on the terminal, that same output should go into the pipe.
    – Barmar
    Commented Jun 26, 2015 at 0:50
  • It should work with egrep. It doesn't work with grep because | is not part of Basic Regular Expression.
    – Barmar
    Commented Jun 26, 2015 at 0:53

2 Answers 2

2

For me, netstat | grep -P '(tcp|udp)' worked.

You may want to use the i flag to ignore the case if necessary.

netstat | grep -Pi '(TcP|UDp)'

About the other answer here, using egrep or grep -e gives the same result. Based on this.

The -P flag was inspired by this post.

Using the option -P, accordingly to man grep, sets the pattern interpreter as . Not sure why it did not work without -P though.

3
  • Good answer, the -e comment should have been a comment to my post rather than being included in your answer though.
    – ShellFish
    Commented Jun 30, 2015 at 20:53
  • I still have not enough reputation to comment on other answers :/ Commented Jul 2, 2015 at 16:40
  • Oh, sorry, should have noticed that. Well at least you got ten points from my upvote. Keep up the good work and you'll have the reputation soon. Try to also markup your posts so they are readable and understandable, this will only improve the quality of your posts. More information here.
    – ShellFish
    Commented Jul 2, 2015 at 16:48
0

outputs the protocol using lower case characters. Try either of the following:

netstat | grep '^\(udp\|tcp\)'

or

netstat | egrep '^(udp|tcp)'

The difference between the two is that supports an extended regular expression syntax in which (, ) and | should not be escaped. As Reuel Ramos Ribeiro noted, egrep is equivalent to using grep -e so alternatively one could use netstat | grep -e '^(udp|tcp)'.

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