我有一个包含多个条目的配置文件。
使用 bash 我如何搜索
New
并删除它和所有与之相关的条目。
Test {
blah..
site {
id
}
location {
id
}
staff {
access {
}
}
}
New {
blah..
site {
id
}
location {
id
}
staff {
access {
}
}
}
Link {
blah..
site {
id
}
location {
id
}
staff {
access {
}
}
}
导致
Test {
blah..
site {
id
}
location {
id
}
staff {
access {
}
}
}
Link {
blah..
site {
id
}
location {
id
}
staff {
access {
}
}
}
我知道我可以使用
grep
找到匹配的结果,但是我如何删除它呢?
例如:
grep -m 1 -A25 New test.txt
编辑 看起来这可以删除输出并给出正确的结果。
grep -m 1 -A25 New test.txt > test | grep -v -x -f test test.txt
但它留下了一个冗余文件test
并且原始文件没有更新。
有没有更好的方法做到这一点,所以没有冗余文件并更新原始文件?
命令
sed 's/^New/,/^}/d'
对我有用。这是我将您的示例粘贴到其中时的输出:
Test {
blah..
site {
id
}
location {
id
}
staff {
access {
}
}
}
Link {
blah..
site {
id
}
location {
id
}
staff {
access {
}
}
}
使用
awk
:
awk '/^New/{f=1} /^}/&&f==1 {f=0;next} !f' file.txt
输出:
Test {
blah..
site {
id
}
location {
id
}
staff {
access {
}
}
}
Link {
blah..
site {
id
}
location {
id
}
staff {
access {
}
}
}
mawk 'BEGIN { FS = RS "*New {"
ORS = RS = RS "}" RS } NF < 2'
1 Test {
2 blah..
3
4 site {
5 id
6 }
7 location {
8 id
9 }
10 staff {
11 access {
12
13 }
14 }
15 }
16
17 Link {
18 blah..
19
20 site {
21 id
22 }
23 location {
24 id
25 }
26 staff {
27 access {
28
29 }
30 }
31 }