我有这样的文件:
subset {
set {
type "car"
product "ww"
dealer "something"
features "0"
wheels 4
}
这可以重复使用不同的“类型”
我想在“集合”中的最后一个}之前插入一些内容
所以它看起来像(不确定awk或sed是否可以某种方式检测到:D之前的行有多少空格):
subset {
set {
type "car"
product "ww"
dealer "something"
features "0"
wheels 4
something
}
我可以用
进行匹配sed "/type.*.car.*/,/\} .... something here..."
文件,我只是想不通。。我找不到“轮子”,因为那可能有所不同。任何帮助将不胜感激。
答案 0 :(得分:1)
这可能对您有用(GNU sed):
sed '/\<type\>.*\<car\>/{h;:a;n;/^\s*}/!ba;x;s/\S.*/something/;G}' file
查找包含必需的type
的行,复制该行,然后读取/打印后续行,直到以右花括号开头的行。交换回到复制的行,并用所需的字符串替换第一个非空格中的所有内容,然后添加包含右花括号的行并打印结果。
答案 1 :(得分:0)
给出:
subset {
set {
type "car"
product "ww"
dealer "something"
features "0"
wheels 4
}
set {
type "second"
product "ww"
dealer "something"
features "0"
wheels 4
}
如果只想在键入“汽车”时添加“内容”,请运行以下命令:
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
答案 2 :(得分:0)
这是另一个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
}
}