sedgnu-sed

sed: remember capture in second expression


I am trying to find occurence of captured pattern and pre-pend next line with captured pattern.

For example:

...
[line 10] #---------- SOLID: tank_phys.0
[line 11]   Shape {
...
[line 22] #---------- SOLID: head_phys.0
[line 23]   Shape {  
...

expected output:

...
[line 10] #---------- SOLID: tank_phys.0
[line 11]   DEF tank Shape {
...
[line 22] #---------- SOLID: head_phys.0
[line 23]   DEF head Shape {   
...

Here is what I have:

sed -rn '/#---------- SOLID: (.*)_phys.0/{n ; s/Shape/DEF <PreviousCapture> Shape/p;}' g4_00.wrl

How can I substitute Shape { with DEF tank Shape { ?

Thanks

GT


Solution

  • With a pure sed solution:

    INPUT:

    $ cat file
    #---------- SOLID: tank_phys.0
      Shape {
    abcdef
    1234
    #---------- SOLID: head_phys.0
      Shape { 
    12345
    gdfg
    

    Command:

    $ sed -rn '/#---------- SOLID: (.*)_phys.0/{p;s/#---------- SOLID: (.*)_phys.0/DEF \1/;N;s/\n//;s/ {2,}/ /;s/^/  /p;b};/#---------- SOLID: (.*)_phys.0/!p' file
    

    OUTPUT:

    #---------- SOLID: tank_phys.0
      DEF tank Shape {
    abcdef
    1234
    #---------- SOLID: head_phys.0
      DEF head Shape { 
    12345
    gdfg
    

    EXPLANATIONS:

    /#---------- SOLID: (.*)_phys.0/{ #this block will be executed on each line respecting the regex /#---------- SOLID: (.*)_phys.0/
    p; #print the line
    s/#---------- SOLID: (.*)_phys.0/DEF \1/; #replace the line content using backreference to form DEF ...
    N;#append next line Shape { to the pattern buffer
    s/\n//;s/ {2,}/ /;s/^/  /p; #remove the new line, add/remove some spaces
    b}; #jump to the end of the statements
    /#---------- SOLID: (.*)_phys.0/!p #lines that does not respect the regex will just be printed