2

我试图找到捕获模式的出现并在下一行之前添加捕获的模式。

例如:

...
[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 {

谢谢

燃气轮机

4

3 回答 3

1

使用纯sed解决方案:

输入:

$ 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
于 2018-03-27T08:11:31.207 回答
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 {
于 2018-03-27T04:07:58.893 回答
0

你可以试试这个 sed

sed -E '
  /SOLID/!b
  N
  s/(^.*SOLID: )([^_]*)(.*\n)([[:blank:]]*)(.*$)/\1\2\3\4DEF \2 \5/
' infile
于 2018-03-27T12:46:17.737 回答