Awk / sed inserts a line between two patterns

I have a G-code file for an CNC machine that should have two lines inserted between patterns. Essentially, I need to write a simple mail processor. Here is a small piece of code from my CAM program:

G00 X-1.663 Y-0.992 Z+0.
G01 X-1.072 Y-0.992
G01 X-1.072 Y-0.874
G01 X-1.663 Y-0.874
G01 X-1.663 Y-0.992
G00 X-3.021 Y-0.992
G01 X-3.021 Y-0.874
G01 X-2.43 Y-0.874
G01 X-2.43 Y-0.992
G01 X-3.021 Y-0.992

I need to insert two lines between G00 and G01 in this order. Thus, the above example would be as follows:

G00 X-1.663 Y-0.992 Z+0.
M51
M04 F.1
G01 X-1.072 Y-0.992
G01 X-1.072 Y-0.874
G01 X-1.663 Y-0.874
G01 X-1.663 Y-0.992
G00 X-3.021 Y-0.992
M51
M04 F.1
G01 X-3.021 Y-0.874
G01 X-2.43 Y-0.874
G01 X-2.43 Y-0.992
G01 X-3.021 Y-0.992

Another thing I need is line breaks, which should be in Windows / DOS style with \ r \ n at the ends. This is due to an old, fickle CNC controller that wants DOS text files. I could use another awk or sed script, but one liner would be preferable. I have tried:

awk '/G00/,/G01/{print $0 RS "M51" RS "M04 F.1";next}1' FILE

ANY G00 G01. G00 G01. , . !

+4
2

awk :

awk '$1=="G00"{p=1} p && $1=="G01"{print "M51"; print "M04 F.1"; p=0} 1' file
G00 X-1.663 Y-0.992 Z+0.
M51
M04 F.1
G01 X-1.072 Y-0.992
G01 X-1.072 Y-0.874
G01 X-1.663 Y-0.874
G01 X-1.663 Y-0.992
G00 X-3.021 Y-0.992
M51
M04 F.1
G01 X-3.021 Y-0.874
G01 X-2.43 Y-0.874
G01 X-2.43 Y-0.992
G01 X-3.021 Y-0.992
+4

- :

awk 'last=="G00" && $1=="G01" {print "M51\nM04 F.1"} {last=$1} 1' file

"G00", - "G01", .

:

G00 X-1.663 Y-0.992 Z+0.
M51
M04 F.1
G01 X-1.072 Y-0.992
G01 X-1.072 Y-0.874
G01 X-1.663 Y-0.874
G01 X-1.663 Y-0.992
G00 X-3.021 Y-0.992
M51
M04 F.1
G01 X-3.021 Y-0.874
G01 X-2.43 Y-0.874
G01 X-2.43 Y-0.992
+3

Source: https://habr.com/ru/post/1548672/


All Articles