替换可能多行模式的每一行的开头
Replace the beginning of every line of a possibly multiline pattern
我正在尝试匹配一个多行模式并修改匹配该模式的每一行,包括第一行,以便在该行的开头添加一个字符(+/-
)
例如,我有:
stuff above
<span>one-liner span</span>
stuff middle
<span>stuff inside
other stuff
</span>
stuff below
我想得到那个:
stuff above
+ <span>one-liner span</span>
stuff middle
+ <span>stuff inside
+ other stuff
+ </span>
stuff below
到目前为止我在那里:
perl -n0e 's/\n(.*<span style="color: green".*?<\/span>)/+/g && print' myfile.html
这里的问题是它只修改了第一行,如果是多行模式,我想修改所有行。
知道怎么做吗?
我正在使用 perl,但如果您认为它更好,我愿意使用其他工具。
谢谢!
一种方法是使用 range operator
perl -wpe'print "+ " if /^\s*<span/ .. /<\/span>/' file
本次使用中的 ..
运算符保持其状态,因此
Once the left operand is true, the range operator stays true until the right operand is true, AFTER which the range operator becomes false again.
它的典型用途恰恰是 select 一系列由给定条件分隔的行。
在这里,我将开头的 span
限制为该行中的第一个非空白内容,而不是结尾的内容,以便允许单行 <span ...>word</span>
部分起作用.
使用范围运算符屏蔽您想要的范围,然后追加到以白色开头的行 space。此代码并未准确给出您想要的内容,但会为您指明正确的方向。
while(<>) {
if( /stuff above/ .. /stuff below/ ){
$_= "+".$_ if /^ +/;
print $_;
}
}
范围运算符是我的最爱之一!
如果您的数据在 'd' 文件中
perl -ne 'if (/^\s*<(span)>.*?(<\/>)?\s*$/) {print "+$&";next if ();$t="</>";do{$_=<>;print "+$_"} until(/$t/) } else {print}' d
gnu sed
sed -E 's/<(span)>.*<\/>/+&/;Tc;b ;:c /^\s*<span>/{s/^/+/;:l n;s/^/+/;/<\/span>/!bl}' d
我正在尝试匹配一个多行模式并修改匹配该模式的每一行,包括第一行,以便在该行的开头添加一个字符(+/-
)
例如,我有:
stuff above
<span>one-liner span</span>
stuff middle
<span>stuff inside
other stuff
</span>
stuff below
我想得到那个:
stuff above
+ <span>one-liner span</span>
stuff middle
+ <span>stuff inside
+ other stuff
+ </span>
stuff below
到目前为止我在那里:
perl -n0e 's/\n(.*<span style="color: green".*?<\/span>)/+/g && print' myfile.html
这里的问题是它只修改了第一行,如果是多行模式,我想修改所有行。
知道怎么做吗?
我正在使用 perl,但如果您认为它更好,我愿意使用其他工具。
谢谢!
一种方法是使用 range operator
perl -wpe'print "+ " if /^\s*<span/ .. /<\/span>/' file
本次使用中的 ..
运算符保持其状态,因此
Once the left operand is true, the range operator stays true until the right operand is true, AFTER which the range operator becomes false again.
它的典型用途恰恰是 select 一系列由给定条件分隔的行。
在这里,我将开头的 span
限制为该行中的第一个非空白内容,而不是结尾的内容,以便允许单行 <span ...>word</span>
部分起作用.
使用范围运算符屏蔽您想要的范围,然后追加到以白色开头的行 space。此代码并未准确给出您想要的内容,但会为您指明正确的方向。
while(<>) {
if( /stuff above/ .. /stuff below/ ){
$_= "+".$_ if /^ +/;
print $_;
}
}
范围运算符是我的最爱之一!
如果您的数据在 'd' 文件中
perl -ne 'if (/^\s*<(span)>.*?(<\/>)?\s*$/) {print "+$&";next if ();$t="</>";do{$_=<>;print "+$_"} until(/$t/) } else {print}' d
gnu sed
sed -E 's/<(span)>.*<\/>/+&/;Tc;b ;:c /^\s*<span>/{s/^/+/;:l n;s/^/+/;/<\/span>/!bl}' d