简体   繁体   English

用sed替换多行-Linux / Ubuntu

[英]Multiline replace with sed - Linux/Ubuntu

Original file looks like this: 原始文件如下所示:

BLABLA ABCABC blabl=
a blabla blabla ABC=
ABC blabla blabla A=
BCABC blabla

The result should look like: 结果应如下所示:

BLABLA DEFDEF blabl=
a blabla blabla DEF=
DEF blabla blabla D=
EFDEF blabla

So all ABCABC should be replaced by DEFDEF , even if there is a linebreak (marked with = ) in the word. 因此,即使单词中有换行符(用=标记),所有ABCABC都应替换为DEFDEF

Is it possible with sed? sed有可能吗?

Sed multiline that works for hyphenating ABCABC at an arbitrary position: sed多行,用于在任意位置将ABCABC连字符:

$ sed -r 'N;s/A(=\n)?B(=\n)?C(=\n)?A(=\n)?B(=\n)?C/D\1E\2F\3D\4E\5F/g;P;D' infile
BLABLD AEFDEF blabl=
a blabla blabla DEF=
DEF blabla blabla D=
EFDEF blabla

N;P;D is the idiomatic way of keeping two lines at a time in the pattern space. N;P;D是在模式空间中一次保留两行的惯用方式。 The substitution checks for ABCABC optionally interspersed with = and a newline at any position, and the substitution inserts back what was captured. ABCABC的替换检查可选地在任意位置插入=和换行符,然后替换插入捕获的内容。

This requires extended regular expressions ( -E in BSD sed) for the ? 这需要为?扩展正则表达式(在BSD sed中为-E? operator. 运营商。 GNU sed supports \\? GNU sed支持\\? in BRE as an extension, though, but all the () would have to be escaped as well. 尽管在BRE中作为扩展名,但是所有()也必须转义。


In case the = just symbolizes a newline and isn't actually there, this simplifies to 如果=只是表示换行符而实际上并不存在,则可以简化为

$ sed -r 'N;s/A(\n?)B(\n?)C(\n?)A(\n?)B(\n?)C/D\1E\2F\3D\4E\5F/g;P;D' infile
BLABLA DEFDEF blabl
a blabla blabla DEF
DEF blabla blabla D
EFDEF blabla

好吧,它不是多行的,但是可以解决您的示例:

sed -r -e 's/ABC/DEF/g' -e 's/AB=/DE=/g' -e 's/A=/D=/g' -e 's/^BC/EF/g' -e 's/^C/F/g' infile

尝试这个,

sed -i -e "s/ABC/DEF/g;s/A/D/g;s/B/E/g;s/C/F/g" filename.txt

Using gnu awk with null RS you can do this in single replacement (using gensub ): 将gnu awk与null RS一起使用,可以一次替换(使用gensub ):

awk -v RS= '{
   print gensub(/A(=\n)?B(=\n)?C(=\n)?A(=\n)?B(=\n)?C/, "D\\1E\\2F\\3D\\4E\\5F", "g", $0)
}' file

Output: 输出:

BLABLA DEFDEF blabl=
a blabla blabla DEF=
DEF blabla blabla D=
EFDEF blabla

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM