我试图用字符串替换一行,但接收来自unknown option to s'或unterminated s' command的sed错误。使用/以外的sigils (尝试了@和#)没有任何效果。
line='<script type="text/javascript" src="<?php echo $jquery_path ?>jQuery.js"></script>'
file_content=$(sed 's:/:\\/:g' jquery.js) # escape /s in replacement content
sed -i -e "s@$line@$file_content@" ./index.phpjquery.js是缩小的源,不应该包含任何换行符。
发布于 2015-08-04 16:29:09
关于哪里出了问题:
jquery.min.js包含@和#字符,因此它们都不像未转义的信号那样安全。jquery.min.js的jquery.min.js操作是转义/s,即使在外部sed实例中使用@s。
要解决这个问题,您可能会更改
file_content=$(sed‘s:/:G’jquery.js)
...to...
file_content=$(sed‘s:@:@:G’jquery.js)另外,如果您没有删除带有许可信息的注释的第一行,替换文件实际上并不仅仅是一行。在sed命令中放置未转义的换行符将终止它。
简单的答案是根本不使用sed。例如,考虑一下gsub_literal,作为defined in BashFAQ #21
gsub_literal() {
# STR cannot be empty
[[ $1 ]] || return
# string manip needed to escape '\'s, so awk doesn't expand '\n' and such
awk -v str="${1//\\/\\\\}" -v rep="${2//\\/\\\\}" '
# get the length of the search string
BEGIN {
len = length(str);
}
{
# empty the output string
out = "";
# continue looping while the search string is in the line
while (i = index($0, str)) {
# append everything up to the search string, and the replacement string
out = out substr($0, 1, i-1) rep;
# remove everything up to and including the first instance of the
# search string from the line
$0 = substr($0, i + len);
}
# append whatever is left
out = out $0;
print out;
}
'
}在您的用例中,这可能如下所示:
gsub_literal \
'<script type="text/javascript" src="<?php echo $jquery_path ?>jQuery.js' \
"$(<../my_files/jquery.js)" \
<index.php >index.php.out && mv index.php.out index.php发布于 2015-08-04 21:47:42
你自己说过你想替换一个字符串。sed不能在字符串上操作,只能在regexp上操作(请参阅Is it possible to escape regex metacharacters reliably with sed)。另一方面,awk可以对字符串进行操作,所以只需使用awk:
awk -v old='<script type="text/javascript" src="<?php echo $jquery_path ?>jQuery.js"></script>' '
NR == FNR { new = new $0 ORS; next }
$0 == old { $0 = new }
{ print }
' jquery.js index.phphttps://stackoverflow.com/questions/31812932
复制相似问题