本站支持 ActivityPub: [email protected]

Sed处理多行结构数据

图片来源: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

参考:

知识共享许可协议
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注