bash 删除字符之前的所有内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5545572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:44:27  来源:igfitidea点击:

bash remove everything before character

bashsedawkgrep

提问by rmartinez

I have the following:

我有以下几点:

netstat -tuna | awk '{ print ; }' | sed -e '1,2d'

which returns:

返回:

10.20.26.143:51697
10.20.26.143:51696
10.20.26.143:51698
10.20.26.143:51693
10.20.26.143:51695
10.20.26.143:51694
:::22
0.0.0.0:68
0.0.0.0:49625
0.0.0.0:5353
:::48727
:::5353

which returns a list of all open ports.. how would i remove everything before the : character? please notice that a few ones have ::: instead of : i just want it to return the ports, remove all text before the last :

它返回所有开放端口的列表.. 我将如何删除 : 字符之前的所有内容?请注意,有几个有 ::: 而不是 : 我只是想让它返回端口,删除最后一个之前的所有文本:

i want it all in one bash command.

我想在一个 bash 命令中完成所有操作。

thanks a lot in advance!

非常感谢!

回答by user unknown

add to your sed-command:

添加到您的 sed 命令:

';s/.*:/:/g'

netstat -tuna | awk '{ print ; }' | sed -e '1,2d;s/.*:/:/g'

should work.

应该管用。

回答by kurumi

Just do it with one awk command. No need to chain too many

只需使用一个 awk 命令即可。无需链接太多

netstat -tuna | awk  'NR>2{ k=split(,a,":");print a[k] }'

or

或者

netstat -tuna | awk  'NR>2{ sub(/.*:/,"",);print  }'

or Ruby(1.9+)

或 Ruby(1.9+)

netstat -tuna | ruby -ane 'puts $F[3].sub(/.*:/,"") if $.>2'

if you want unique ports,

如果你想要独特的端口,

netstat -tuna | awk  'NR>2{ sub(/.*:/,"",); uniq[] }END{ for(i in uniq) print i }'

回答by SiegeX

So apparently, you can tuna network, but you can't tuna fish

显然,您可以使用金枪鱼网络,但您不能使用金枪鱼

The following will print all open ports

以下将打印所有打开的端口

netstat -tuna | awk -F':+| +' 'NR>2{print }'

The following will print all uniqueopen ports, i.e. no duplicates sorted in ascending order

以下将打印所有唯一的开放端口,即没有按升序排序的重复项

netstat -tuna | awk -F':+| +' 'NR>2{print }' | sort -nu