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 ответа
Решение
С чистым 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
После простого 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 {
Вы можете попробовать этот сед
sed -E '
/SOLID/!b
N
s/(^.*SOLID: )([^_]*)(.*\n)([[:blank:]]*)(.*$)/\1\2\3\4DEF \2 \5/
' infile