[英]Insert text before the last line betweeen two matches in sed or awk
我有這樣的文件:
subset {
set {
type "car"
product "ww"
dealer "something"
features "0"
wheels 4
}
這可以重復使用不同的“類型”
我想在“set”中的最后一個 } 之前插入一些東西
所以它看起來像(不確定 awk 或 sed 是否可以以某種方式檢測到前面有多少個空格:D):
subset {
set {
type "car"
product "ww"
dealer "something"
features "0"
wheels 4
something
}
我可以匹配它
sed "/type.*.car.*/,/\} .... something here..."
文件我只是想不通..我不能尋找“輪子”,因為那可能是不同的東西。 任何幫助將非常感激。
這可能對您有用(GNU sed):
sed '/\<type\>.*\<car\>/{h;:a;n;/^\s*}/!ba;x;s/\S.*/something/;G}' file
查找包含所需type
的行,復制該行,然后讀取/打印后續行,直到以右花括號開頭的行。 切換回復制的行並將第一個非空格中的所有內容替換為所需的字符串 append 包含右花括號的行並打印結果。
鑒於:
subset {
set {
type "car"
product "ww"
dealer "something"
features "0"
wheels 4
}
set {
type "second"
product "ww"
dealer "something"
features "0"
wheels 4
}
如果您只想在鍵入“car”時添加“something”,請運行以下命令:
perl -0777 -ape 's/set\h*{[^}]*type "car"[^}]*\K(?=\n\h+})/\n\tsomething/g' file.txt
subset {
set {
type "car"
product "ww"
dealer "something"
features "0"
wheels 4
something
}
set {
type "second"
product "ww"
dealer "something"
features "0"
wheels 4
}
解釋:
s/ # substitute
set # literally
\h* # 0 or more horizontal spaces
{ # opening curly brace
[^}]* # 0 or more non curly brace
type "car" # literally
[^}]* # 0 or more non curly brace
\K # forget all we have seen until this position
(?=\n\h+}) # positive lookahead, make sure we have after a linefeed and some horizontal spaces and a closing curly brace
/ # with
\n # linefeed
\t # a tab
something # whatever you want
/g # end subs, global
這是另一個awk
腳本(標准 Linux gawk)。
/ +set {/,/ +}/{
if($0 ~ /type "car"/ ) f = 1;
if($0 ~ / +}/ && f == 1) {
print " something";
f = 0;
}
}1
subset {
set {
type "car"
product "ww"
dealer "something"
features "0"
wheels 4
}
set {
type "baot"
product "nice"
dealer "here"
features "1"
wheels 0
}
set {
type "horse"
product "too"
dealer "very"
features "2"
wheels 0
}
}
awk -f script.awk input.txt
subset {
set {
type "car"
product "ww"
dealer "something"
features "0"
wheels 4
something
}
set {
type "baot"
product "nice"
dealer "here"
features "1"
wheels 0
}
set {
type "horse"
product "too"
dealer "very"
features "2"
wheels 0
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.