用sed替换多行字符串

哪里

我有一个基本上是INI / CFG文件的文件,看起来像这样:

[thing-a]
attribute1=foo
attribute2=bar
attribute3=foobar
attribute4=barfoo

[thing-b]
attribute1=dog
attribute3=foofoo
attribute4=castles

[thing-c]
attribute1=foo
attribute4=barfoo

[thing-d]
attribute1=123455
attribute2=dogs
attribute3=biscuits
attribute4=1234

每个“事物”都有一组属性,可以包括所有相同的属性或其中的一个子集。

我正在尝试编写一个小的bash脚本,用更广泛的脚本中的其他位置生成的预定义块$ a1,$ a2和$ a3替换'thing-c'的属性:

NEW_BLOCK="[thing-c]
attribute1=${a1}
attribute2=${a2}
attribute3=${a3}"

我可以用sed找到正确的块,如下所示:

THING_BLOCK=$(sed -nr "/^\[thing-c\]/ { :l /^\s*[^#].*/ p; n; /^\[/ q; b l; }" ./myThingFile)

我不确定我是否掉进了兔子洞,或者对此做了什么,我很确定有更好的方法。

我想做的是:

sed "s/${THING_BLOCK}/${NEW_BLOCK}/"

但是我还不太了解这方面的多行方面,也不确定最好的方法是什么。

有没有一种方法可以进行这种多行查找并用sed替换(或者用bash更好的方法)

阿努巴瓦

有没有一种方法可以进行这种多行查找和替换...

是的,确实有更好的方法,尽管使用了awk

awk -v blk="$NEW_BLOCK" -v RS= '{ORS = RT} $1 == "[thing-c]" {$0 = blk} 1' file

使用-v RS=我们使用一个空的记录分隔符,该记录分隔符将输入文件中的记录拆分为每一行。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章