bash 找到匹配后添加新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24707352/
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
add a new line after match is found
提问by theuniverseisflat
I want to add a new line after I search for number 64 in a file. I like to use awk or sed to do this.
我想在文件中搜索数字 64 后添加一个新行。我喜欢使用 awk 或 sed 来做到这一点。
64 bytes from 170.198.42.128: icmp_seq=1 ttl=60 time=83.4 ms 64 bytes from
170.198.42.128: icmp_seq=2 ttl=60 time=76.6 ms 64 bytes from 170.198.42.128: icmp_seq=3
ttl=60 time=70.8 ms 64 bytes from 170.198.42.128: icmp_seq=4 ttl=60 time=76.6 ms ---
170.198.42.128 ping statistics --- 4 packets transmitted, 4 received, 0% packet loss, time
3000ms rtt min/avg/max/mdev = 70.861/76.924/83.493/4.473 ms
I use this command
我用这个命令
cat file | sed 's/64/\n/g'
but this replaces the number 64. I want just to break the pattern and display the ping command pattern starting with 64 properly
但这取代了数字 64。我只想打破模式并正确显示以 64 开头的 ping 命令模式
I tried using append and insert mode ..but not using them correctly
我尝试使用附加和插入模式..但没有正确使用它们
Need help
需要帮忙
回答by Barmar
In a substitution, &
in the replacement will be replaced with whatever matched. So:
在替换中,&
在替换中将替换为匹配的任何内容。所以:
sed 's/64/\n&/g' file
回答by anubhava
This sed
command should work with both gnu and BSD sed versions:
此sed
命令应该适用于 gnu 和 BSD sed 版本:
sed $'s/64/\\n&/g' file
64 bytes from 170.198.42.128: icmp_seq=1 ttl=60 time=83.4 ms
64 bytes from
170.198.42.128: icmp_seq=2 ttl=60 time=76.6 ms
64 bytes from 170.198.42.128: icmp_seq=3
ttl=60 time=70.8 ms
64 bytes from 170.198.42.128: icmp_seq=4 ttl=60 time=76.6 ms ---
170.198.42.128 ping statistics --- 4 packets transmitted, 4 received, 0% packet loss, time
3000ms rtt min/avg/max/mdev = 70.861/76.924/83.493/4.473 ms
Update:Here is gnu awk command to do the same:
更新:这是执行相同操作的 gnu awk 命令:
awk '1' RS='64' ORS='\n64' file
回答by Ed Morton
This might be more like what you really need (uses GNU awk for multi-char RS):
这可能更像您真正需要的(使用 GNU awk 进行多字符 RS):
$ gawk -v RS='^$' '{gsub(/[[:space:]]+/," "); gsub(/(\<[[:digit:]]+\> bytes|---)/,"\n&"); sub(/^\n/,"")}1' file
64 bytes from 170.198.42.128: icmp_seq=1 ttl=60 time=83.4 ms
64 bytes from 170.198.42.128: icmp_seq=2 ttl=60 time=76.6 ms
64 bytes from 170.198.42.128: icmp_seq=3 ttl=60 time=70.8 ms
64 bytes from 170.198.42.128: icmp_seq=4 ttl=60 time=76.6 ms
--- 170.198.42.128 ping statistics
--- 4 packets transmitted, 4 received, 0% packet loss, time 3000ms rtt min/avg/max/mdev = 70.861/76.924/83.493/4.473 ms