bla*_*899 9 sed perl text-processing
我有一个大文件,里面有特殊字符。那里有一个多行代码,我想用sed
.
这个:
text = "\
------ ------\n\n\
This message was automatically generated by email software\n\
The delivery of your message has not been affected.\n\n\
------ ------\n\n"
Run Code Online (Sandbox Code Playgroud)
需要变成这样:
text = ""
Run Code Online (Sandbox Code Playgroud)
我尝试了以下代码,但没有运气:
sed -i '/ text = "*/ {N; s/ text = .*affected.\./ text = ""/g}' /etc/exim.conf
Run Code Online (Sandbox Code Playgroud)
它不会替换任何东西,也不会显示任何错误消息
我一直在玩它,但我尝试的一切都不起作用。
cho*_*oba 15
Perl 来拯救:
perl -i~ -0777 -pe 's/text = "[^"]+"/text = ""/g' input-file
Run Code Online (Sandbox Code Playgroud)
-i~
将“就地”编辑文件,留下备份副本-0777
一次读取整个文件,而不是逐行读取替换的s///
工作方式与 sed 中的类似(即它匹配text = "
后跟除双引号外的任何内容多次直到双引号),但在这种情况下,它适用于整个文件。
您必须检查模式空间,N
如果不匹配,则继续拉入ext 行,例如
sed '/text = "/{ # if line matches text = "
:b # label b
$!N # pull in the next line (if not the last one)
/"$/!bb # if pattern space doesn't end with " go to label b
s/".*"/""/ # else remove everything between the quotes
}' infile
Run Code Online (Sandbox Code Playgroud)
与gnu sed
您可以把它写成
sed '/text = "/{:b;$!N;/"$/!bb;s/".*"/""/}' infile
Run Code Online (Sandbox Code Playgroud)
但这不是很有效,最好只选择范围/text = "/,/"/
,修改第一行并删除其余部分:
sed '/text = "/,/"/{ # in this range
/text = "/!d # delete all lines not matching text = "
s/\\/"/ # replace the backslash with quotes (this is only
}' infile # executed if the previous d wasn't executed)
Run Code Online (Sandbox Code Playgroud)
再次,gnu sed
你可以把它写成一行:
sed '/text = "/,/"/{/text = "/!d;s/\\/"/}' infile
Run Code Online (Sandbox Code Playgroud)