如何 sed 具有特定模式的文本块? [英] How to sed a block of text with specific pattern?
问题描述
我有这样的文件
...
%pythons
Albino
Black Bee
Bumble Bee
%end
%boa
Albino
Jungle
Pastel
%end
...
为了保存或替换目的,我想从这个文件匹配模式中 sed 整个块.块中的行数可能非常多.我需要通用的解决方案.我正在寻找这样的东西
I would like to sed one whole block from this file matching pattern for saving or sustitution purposes.Number of lines in a block may very. I need common solution. I'm looking for something like this
sed -n '/^%boa(**something here**)^%end$//p' snakes > boa
sed 's/^%boa(**something here**)^%end$/(**new block**)/' snakes > snakes_updated
我正在专门寻找 sed 解决方案.任何带有解释的建议将不胜感激.
I'm looking specifically for sed solution. Any suggestions with explanation would be very appreciated.
推荐答案
这可能对你有用(GNU sed):
This might work for you (GNU sed):
sed -i -e '/%boa/,/%end/{w fileb' -e '/%end/!d;r filec' -e 'd}' filea
这会将 %boa
和 %end
之间的部分写入 fileb 并将其替换为 filec 的内容.使用 -i
标志将 filea 的内容替换为已编辑的操作.
This writes the section between %boa
and %end
to fileb and replaces it with the contents of filec. The contents of filea is replaced by the edited operations by using the -i
flag.
这篇关于如何 sed 具有特定模式的文本块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!