图片来源:https://www.pixiv.net/artworks/81733152
使用sed处理类似下面这样的有独立的首尾特征的多行结构数据,实现增删改查
Apple:
{
price = 1.24;
count = 5;
on_sale = true;
from = shanxi;
};
Banana:
{
price = 4.12;
count = 1;
on_sale = false;
};
Pear:
{
price = 2.14;
on_sale = true;
count = 7;
};
增
给梨添加一个产地字段(from = guangxi
)
sed -i.bak '/Pear:/!b;n;a\ \ \ \ from = guangxi;' fruit.conf
删
删除苹果的产地
sed -i.bak '/Apple:/,/};/{/ from =/d}' fruit.conf
改
修改香蕉的价格
sed -i.bak -r '/Banana:/,/};/s/^( +price) ?= ?.*$/\1 = 2.88;/' fruit.conf
查
打印所有打折的水果(on_sale = true
)
单行版本
sed -n 'H;/};/!b;g;/ on_sale = true;/!b c;p;: c;s/.*//;h' fruit.conf
多行版本
#!/usr/bin/sed -nf
H
/};/!b
g
/ on_sale = true;/!b clear
p
: clear
s/.*//
h
参考:
- stack overflow——Does deleting sed pattern space with ‘d’ erase hold space as well?
- https://linux.liuxfe.com/man1:sed
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。