Reputation: 881
I want to add a newline after number 64, using awk or sed, in ping output such as this:
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've tried
cat file | sed 's/64/\n/g'
but this replaces the number 64. I want to break the pattern and display the ping command pattern starting with 64 properly.
I tried using append and insert mode ..but not using them correctly
Upvotes: 7
Views: 23054
Reputation: 2548
For more general case (add a text and newline after/before the match) I recommend using the following commands.
This approach is better than /a sed parameter, because /a does not work on some operating systems or old sed versions.
If REPLACE_STR is empty it will add just a newline after/before the PATTERN_STR, that is the asked question is a particular case (PATTERN_STR=64, REPLACE_STR=).
Adds REPLACE_STR string as a new line after the matched string PATTERN_STR:
sed $'s/PATTERN_STR/&\\\nREPLACE_STR/' file
Adds REPLACE_STR string as a new line before the matched string PATTERN_STR:
sed $'s/PATTERN_STR/REPLACE_STR\\\n&/' file
Upvotes: 0
Reputation: 203149
This might be more like what you really need (uses GNU awk for multi-char 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
Upvotes: 2
Reputation: 784898
This sed
command should work with both gnu and BSD sed versions:
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:
awk '1' RS='64' ORS='\n64' file
Upvotes: 7
Reputation: 780688
In a substitution, &
in the replacement will be replaced with whatever matched. So:
sed 's/64/\n&/g' file
Upvotes: 9