Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a newline after match is found

Tags:

bash

sed

awk

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

like image 903
theuniverseisflat Avatar asked Jul 11 '14 22:07

theuniverseisflat


People also ask

How do I add a line to a certain line number?

In the first line, we added the line number for insertion. Secondly, we specified the insert action in the same line. Then, in the next line, we added the phrase we wanted to insert. In the end, we need to put a dot (.) to end the input mode and then add xit to save the changes and quit the editor.

How do you add a new line in sed?

There are different ways to insert a new line in a file using sed, such as using the “a” command, the “i” command, or the substitution command, “s“.

How do I add a new line to a file?

Sometimes we need to work with a file for programming purposes, and the new line requires to add at the end of the file. This appending task can be done by using 'echo' and 'tee' commands. Using '>>' with 'echo' command appends a line to a file.


2 Answers

In a substitution, & in the replacement will be replaced with whatever matched. So:

sed 's/64/\n&/g' file
like image 198
Barmar Avatar answered Nov 16 '22 04:11

Barmar


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
like image 20
anubhava Avatar answered Nov 16 '22 03:11

anubhava