Regex 如何使用特定的模式创建文本块?
我有一个像这样的文件Regex 如何使用特定的模式创建文本块?,regex,bash,sed,Regex,Bash,Sed,我有一个像这样的文件 ... %pythons Albino Black Bee Bumble Bee %end %boa Albino Jungle Pastel %end ... 为了保存或替换的目的,我想从这个文件匹配模式中删除一个完整的块。一个块中的行数可能非常多。我需要共同的解决方案。 我在找这样的东西 sed -n '/^%boa(**something here**)^%end$//p' snakes > boa sed 's/^%boa(**something here
...
%pythons
Albino
Black Bee
Bumble Bee
%end
%boa
Albino
Jungle
Pastel
%end
...
为了保存或替换的目的,我想从这个文件匹配模式中删除一个完整的块。一个块中的行数可能非常多。我需要共同的解决方案。
我在找这样的东西
sed -n '/^%boa(**something here**)^%end$//p' snakes > boa
sed 's/^%boa(**something here**)^%end$/(**new block**)/' snakes > snakes_updated
我专门寻找sed解决方案。如有任何解释性建议,将不胜感激 看起来你想要这样的东西
$ sed -n '/^%boa$/,/^%end$/p' file
%boa
Albino
Jungle
Pastel
%end
它打印特定范围内的行。使用
perl-0
您可以轻松搜索并替换此文件中的一个块:
perl -0pe 's~(?ms)\R%boa.*%end(\R|\z)~\n---\nfoo\nbar\nbaz\n---\n~' file
...
%pythons
Albino
Black Bee
Bumble Bee
%end
---
foo
bar
baz
---
...
如果我理解得很好,你可以这样做:
sed -i.bak '/^%boa/,/%end/ {
wboas
d
}' file
使用,您正在将/^%boa/,/%end/
之间的内容写入文件boas使用,您将删除原始文件中的这些行(在的帮助下) 原始文件:
$ cat file
...
%pythons
Albino
Black Bee
Bumble Bee
%end
%boa
Albino
Jungle
Pastel
%end
...
例子
此外,如果需要用其他内容替换块(比如说
“hello\n world”
),可以将其附加以下内容:
例子
这可能适用于您(GNU-sed):
这会将
%boa
和%end
之间的部分写入fileb,并将其替换为filec的内容。通过使用-i
标志,文件a的内容被编辑的操作替换。要删除块还是只删除块?我需要将此块保存到另一个文件中,或者在需要时用另一个块替换它谢谢!有没有办法用这种模式将这样的块替换为另一块文本?使用sed的/pattern/block/'file?将块保存到另一个文件sed-n'/^%boa$/,/^%end$/p'infle>outfile
,但我不知道如何进行块替换。感谢您的回答。
$ sed -i.bak '/^%boa/,/%end/ {
> wboas
> d
> }' file
$ cat boas
%boa
Albino
Jungle
Pastel
%end
$ cat file
...
%pythons
Albino
Black Bee
Bumble Bee
%end
...
sed -i.bak '/^%boa/,/%end/ {
wboas
/^%boa/a \
hello \
world
d
}' file
$ sed -i.bak '/^%boa/,/%end/ {
> wboas
> /^%boa/a \
> hello \
> world
> d
> }' file
$ cat file
...
%pythons
Albino
Black Bee
Bumble Bee
%end
hello
world
...
$ cat boas
%boa
Albino
Jungle
Pastel
%end
sed -i -e '/%boa/,/%end/{w fileb' -e '/%end/!d;r filec' -e 'd}' filea