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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
makansij
  • 9,303
  • 37
  • 105
  • 183
  • 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 Jun 26 '15 at 00: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. – brandonscript Jun 26 '15 at 00: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 Jun 26 '15 at 00:50
  • It should work with `egrep`. It doesn't work with `grep` because `|` is not part of Basic Regular Expression. – Barmar Jun 26 '15 at 00:53

2 Answers2

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.

Community
  • 1
  • 1
Reuel Ribeiro
  • 1,419
  • 14
  • 23
  • Good answer, the `-e` comment should have been a comment to my post rather than being included in your answer though. – ShellFish Jun 30 '15 at 20:53
  • I still have not enough reputation to comment on other answers :/ – Reuel Ribeiro Jul 02 '15 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](http://stackoverflow.com/editing-help). – ShellFish Jul 02 '15 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)'.

Community
  • 1
  • 1
ShellFish
  • 4,351
  • 1
  • 20
  • 33