grep 的正则表达式不起作用?
regular expression with grep not working?
我是 运行ning cygwin,grep 2.21 on Windows 7.
我正在尝试从 netstat 获取所有 tcp 连接,所以我 运行 以下内容:
netstat | grep -i "^(TCP|UDP)"
现在,它returns没什么,但是当我运行netstat
它清楚returns一堆tcp连接。我也试过了:
netstat | egrep -i "^(TCP|UDP)"
也returns没什么。我在这里错过了什么?我认为插入符号的意思是 "begins with"。谢谢
netstat 使用小写字符输出协议。尝试以下任一方法:
netstat | grep '^\(udp\|tcp\)'
或
netstat | egrep '^(udp|tcp)'
两者的区别在于egrep supports an extended regular expression syntax in which (
, )
and |
should not be escaped. As Reuel Ramos Ribeiro注意到,
egrep
等同于使用 grep -e
,因此也可以使用 netstat | grep -e '^(udp|tcp)'
。
对我来说,netstat | grep -P '(tcp|udp)'
有效。
如有必要,您可能希望使用 i
标志来忽略大小写。
netstat | grep -Pi '(TcP|UDp)'
关于这里的另一个答案,使用 egrep
或 grep -e
给出相同的结果。基于 this.
-P
标志的灵感来自 this post。
根据 man grep
使用选项 -P
,将模式解释器设置为 perl。不知道为什么没有 -P
它就不能工作。
我是 运行ning cygwin,grep 2.21 on Windows 7.
我正在尝试从 netstat 获取所有 tcp 连接,所以我 运行 以下内容:
netstat | grep -i "^(TCP|UDP)"
现在,它returns没什么,但是当我运行netstat
它清楚returns一堆tcp连接。我也试过了:
netstat | egrep -i "^(TCP|UDP)"
也returns没什么。我在这里错过了什么?我认为插入符号的意思是 "begins with"。谢谢
netstat 使用小写字符输出协议。尝试以下任一方法:
netstat | grep '^\(udp\|tcp\)'
或
netstat | egrep '^(udp|tcp)'
两者的区别在于egrep supports an extended regular expression syntax in which (
, )
and |
should not be escaped. As Reuel Ramos Ribeiro注意到,
egrep
等同于使用 grep -e
,因此也可以使用 netstat | grep -e '^(udp|tcp)'
。
对我来说,netstat | grep -P '(tcp|udp)'
有效。
如有必要,您可能希望使用 i
标志来忽略大小写。
netstat | grep -Pi '(TcP|UDp)'
关于这里的另一个答案,使用 egrep
或 grep -e
给出相同的结果。基于 this.
-P
标志的灵感来自 this post。
根据 man grep
使用选项 -P
,将模式解释器设置为 perl。不知道为什么没有 -P
它就不能工作。