With this command I am trying to insert M09 between two patterns of M502 and the second line since M502 that looks like X41.5Y251.5T201.
Specifically I am trying to insert M09 before the last line.
sed -i "/M502/{:a;N;/\(.*\)T\([0-9]\ \)/!ba;N;s/\(.*\)\n\(.*\)T\([0-9]\ \)/\1\nM09\n\2T\3/}" *.nc
Result:
M502
M09
X1287.2Y353.28T324
..........
G27X-310.27
X41.5Y251.5T201
Should be:
M502
X1287.2Y353.28T324
..........
G27X-310.27
M09
X41.5Y251.5T201
I am trying to match the last line with \(.*\)T\([0-9]\ \)
, but that picks up the second line. How do I make sed ignore the first match of this expression?
I stress that I could have an undertermined amount of such text blocks and I need to insert M09 for every one.
CodePudding user response:
How do I match the second instance of
\(.*\)T\([0-9]\ \)
? It must be an expression. Thanks for the help.
Assuming that you would like to insert some text just before the line that matches the the above regex for the 2th time, then you should consider using awk, as then you could do something like this:
$ awk '/.*T[0-9][0-9]*/ { n } !p && n == 2 { print "M09"; p = 1 } 1' input.txt
M502
X1287.2Y353.28T324
..........
G27X-310.27
M09
X41.5Y251.5T201
The breakdown of the above command is:
/.*T[0-9][0-9]*/ { n } # Everytime the regex match add one to `n`
!p && n == 2 { print "M09"; p = 1 } # If n = 2 and we havn't printed a header yet,
# then print "M09"
1 # Print every line
CodePudding user response:
With your shown samples, please try following awk
code.
awk '
/.*T[0-9][0-9]*/{ found=1 }
FNR==1 { prev=$0; next }
{
print prev
prev=$0
}
END{
if(found) { print "M09" }
print prev
}
' Input_file
Above code will only print the values on terminal, in case you want to save output into Input_file itself then append > temp && mv temp Input_file
to above code.