[英]How to replace multi line text in html file with a shell script?
I have an html file in which I want to replace a style using a shell script using the function sed
. 我有一个html文件,我想使用
sed
函数使用shell脚本替换样式。 I want to replace: 我想替换:
pre {
font-size: inherit;
line-height: inherit;
}
with: 有:
pre {
font-size: 18px;
/*line-height: inherit;*/
}
I tried the following: 我尝试了以下方法:
sed -i 's/pre {\n font-size: inherit;\n line-height:
inherit;\n}/pre {\n font-size: 18px;\n \/\*line-height:
inherit;\*\/\n}/g' /path/file.html
which runs without any error but does not replace the text. 它运行没有任何错误,但不替换文本。 Note that I'm including tabs to fine-tune the text pattern.
请注意,我包含用于微调文本模式的选项卡。 I'm working on ubuntu 18.
我正在研究ubuntu 18。
Any suggestion will be very grateful. 任何建议都将非常感激。
You can use matched pattern referencing in sed like: 您可以在sed中使用匹配的模式引用,如:
sed -i 's/line-height: inherit;/\/*&*\//g' /path/file.html
Here, we use line-height: inherit;
在这里,我们使用
line-height: inherit;
to match the search pattern. 匹配搜索模式。 You could also extend this as a regex instead
您也可以将其扩展为正则表达式
&
is used to reference the matched text and we put the \\/*
and *\\/
as the enclosing characters &
用于引用匹配的文本,我们将\\/*
和*\\/
作为封闭的字符
sed -Ei '
/^\s*pre\s*\{\s*$/,/^\s*}\s*$/ {
/^\s*line-height:\s*inherit\s*;\s*$/ s#^(.*)$#/*&*/#;
}
' /path/file.html
The first pair of patterns establishes a range between which the code block inside the curlies will be executed - from pre {
to }
. 第一对模式建立了一个范围,在该范围之间将执行curlies中的代码块 - 从
pre {
到}
。
Inside the block, the pattern establishes which lines will be edited by the substitution, so that it only comments the line-height
directives. 在块内部,模式确定将通过替换编辑哪些行,以便它仅注释
line-height
指令。
When matched, it comments the whole line (preserving the whitespace). 匹配时,它会对整行进行注释(保留空白)。
PS - PS -
don't use -iE, that fails. 不要使用-iE,那就失败了。
-Ei works. -Ei的作品。 ;)
;)
PH PH
Based on @PaulHodges answer this works perfectly: 根据@PaulHodges的回答,这非常有效:
sed -Ei '/^\s*pre\s*\{\s*$/,/^\s*}\s*$/ {/^\s*font-size:\s*inherit\s*;\s*$/ s#^(.*)$#
font-size: 18px;#; /^\s*line-height:\s*inherit\s*;\s*$/ s#^(.*)$#/*&*/#;}' /path/file.html
Thank you all for your answers! 谢谢大家的答案!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.