2

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

user1301295
  • 674
  • 1
  • 6
  • 15

3 Answers3

1

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
Allan
  • 12,117
  • 3
  • 27
  • 51
0

Following simple awk may help you on same.

awk '/#---------- SOLID/{print;sub(/_.*/,"",$NF);val=$NF;getline;sub("Shape {","DEF " val " &")} 1'  Input_file

Output will be as follows.

[line 10] #---------- SOLID: tank_phys.0
[line 11]   DEF tank Shape {
...
[line 22] #---------- SOLID: head_phys.0
[line 23]   DEF head Shape {
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • I updated the input to make clear that the lines are not always same, so this awk solution does not work, thanks – user1301295 Mar 27 '18 at 04:26
  • @user1301295, your output is NOT looking consistent in your post shown why `{` is not there for first occurrence of `shape` ? If it is a typo then you would have tried my code I just tested it is working fine only, let me know on same? – RavinderSingh13 Mar 27 '18 at 04:28
  • Edit made, thanks. Coul you explain the code more, I'm only just learning sed and awk is new to me – user1301295 Mar 27 '18 at 04:44
  • @user1301295, sure edited the code as per your need, will add explanation too now in short time, cheers :) – RavinderSingh13 Mar 27 '18 at 05:50
0

You can try this sed

sed -E '
  /SOLID/!b
  N
  s/(^.*SOLID: )([^_]*)(.*\n)([[:blank:]]*)(.*$)/\1\2\3\4DEF \2 \5/
' infile
ctac_
  • 2,413
  • 2
  • 7
  • 17