如何删除或替换两个模式之间的多行文本
我想在我的一些脚本中添加一些客户标志,以便在 shell 脚本打包之前对其进行解析。
比方说,删除之间的所有多行文本
^([#]|[//]){0,1}[_]+NOT_FOR_CUSTOMER_BEGIN[_]+n
和之间
^([#]|[//]){0,1}[_]+NOT_FOR_CUSTOMER_END[_]+n
我希望它具有容错性(关于“_”的数量),这就是我使用正则表达式的原因。
例如:
之前.foo
i want this
#____NOT_FOR_CUSTOMER_BEGIN________
not this
nor this
#________NOT_FOR_CUSTOMER_END____
and this
//____NOT_FOR_CUSTOMER_BEGIN__
not this again
nor this again
//__________NOT_FOR_CUSTOMER_END____
and this again
会变成:
后.foo
i want this
and this
and this again
我宁愿使用 sed,但欢迎任何聪明的解决方案:)
像这样的东西:
cat before.foo | tr 'n' 'a' | sed -r 's/([#]|[//]){0,1}[_]+NOT_FOR_CUSTOMER_BEGIN[_]+a.*a([#]|[//]){0,1}[_]+NOT_FOR_CUSTOMER_END[_]+a/a/g' | tr 'a' 'n' > after.foo
回答
sed 是处理这个问题的最简单的工具,因为它可以删除从开始模式到结束模式的行:
sed -E '/_+NOT_FOR_CUSTOMER_BEGIN_+/,/_+NOT_FOR_CUSTOMER_END_+/d' file
i want this
and this
and this again
如果您正在寻找awk解决方案,那么这里有一个更简单的方法awk:
awk '/_+NOT_FOR_CUSTOMER_BEGIN_+/,/_+NOT_FOR_CUSTOMER_END_+/{next} 1' file