sed: -e expression #1, char 103: unknown option to `s'

时间:2023-01-01 20:12:59

用shell脚本对服务器配置文件进行修改,目的是将下面三行字符串中字符串“(C)”之后的内容删除。

ums.newcopyright.zh_CN=(C) 1998-2015 ÖÐÐË͚Ѷ¹É·ÝÓÐÏÞ¹«ËŸ °æÈšËùÓÐ
ums.newcopyright.en_US=(C) 1998-2015 ZTD Corporation. All rights reserved
ums.newcopyright.ru_RU=(C) 1998-2015 §¬§à§â§á§à§â§Ñ§è§Ú§ñ ZTD. §£§ã§Ö §á§â§Ñ§Ó§Ñ §Ù§Ñ§ë§Ú§ë§Ö§ß§í

考虑用sed替换实现:

#gedit ums-server/works/global/deploy/deploy-usf.properties
deploy_usf_file=./ums-server/works/global/deploy/deploy-usf.properties
newcpcn='ums.newcopyright.zh_CN=(C)'
newcpus='ums.newcopyright.en_US=(C)'
newcpru='ums.newcopyright.ru_RU=(C)'
newcpcn_line=`grep $newcpcn $deploy_usf_file`
newcpus_line=`grep $newcpus $deploy_usf_file`
newcpru_line=`grep $newcpru $deploy_usf_file`
if [ -n "$newcpcn_line" -a -n "$newcpus_line" -a -n "$newcpru_line" ];then
    sed -i "s#${newcpcn_line}#${newcpcn}#g" $deploy_usf_file
    sed -i "s#${newcpus_line}#${newcpus}#g" $deploy_usf_file
    sed -i "s#${newcpru_line}#${newcpru}#g" $deploy_usf_file
    if [ "$?" -eq 0 ]; then
        echo "[10] set newcopyright statement in $deploy_usf_file ok."
    fi
else
    echo "[10] error: set newcopyright statement in $deploy_usf_file fail."
fi

避免替换文本中含有分隔符/,采用#作为分隔符。运行脚本,提示错误:

sed: -e expression #1, char 103: unknown option to `s'

检查脚本发现,类似的三行替换操作,前两行没有问题,报错在第三行,替换失败。怀疑是待替换的字符串中含有分隔符#(后面分析,可能不是这个原因!!)

newcpcn等三个变量的定义里用到了单引号,将字符串中的所有meta关闭,应该是没有错的。

问题应该还是由于第三行中的字符串比较复杂,在表示字符串变量时出了问题,还没有搞明白!!学习下shell十三问再说吧Σ( ° △ °|||)︴

换个思路解决。

理解为将以newcpru为首的整行字符串替换为newcpru,用到整行替换sed整行替换参数c:

#gedit ums-server/works/global/deploy/deploy-usf.properties
deploy_usf_file=./ums-server/works/global/deploy/deploy-usf.properties
newcpcn='ums.newcopyright.zh_CN=(C)'
newcpus='ums.newcopyright.en_US=(C)'
newcpru='ums.newcopyright.ru_RU=(C)'
newcpcn_line=`grep $newcpcn $deploy_usf_file`
newcpus_line=`grep $newcpus $deploy_usf_file`
newcpru_line=`grep $newcpru $deploy_usf_file`
if [ -n "$newcpcn_line" -a -n "$newcpus_line" -a -n "$newcpru_line" ];then
    sed -i "/^$newcpcn/c$newcpcn" $deploy_usf_file
    sed -i "/^$newcpus/c$newcpus" $deploy_usf_file
    sed -i "/^$newcpru/c$newcpru" $deploy_usf_file
    if [ "$?" -eq 0 ]; then
        echo "[10] set newcopyright statement in $deploy_usf_file ok."
    fi
else
    echo "[10] error: set newcopyright statement in $deploy_usf_file fail."
fi


分析待续,欢迎达人释疑!!