sed:记住第二个表达式中的捕获

时间:2018-03-27 03:54:08

标签: sed gnu-sed

我正在尝试找到捕获的模式的出现并使用捕获的模式预先挂起下一行。

例如:

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

预期产出:

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

这就是我所拥有的:

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

如何将Shape {替换为DEF tank Shape {

谢谢

GT

3 个答案:

答案 0 :(得分:1)

使用纯sed解决方案:

<强> INPUT:

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

<强>命令:

$ 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

<强>输出:

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

<强>解释:

/#---------- 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

答案 1 :(得分:0)

关注简单awk可能对您有所帮助。

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

输出如下。

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

答案 2 :(得分:0)

你可以试试这个sed

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