简体   繁体   English

如何使用sed查找并替换为特殊字符?

[英]How to find and replace with special characters using sed?

I want to replace the ip '100.45.9.147' with $(cat apiServer.txt) . 我想用$(cat apiServer.txt)替换'100.45.9.147' A non inplace update works but when i try to use sed's in-place update i get error :- 非就地更新有效,但是当我尝试使用sed的就地更新时,出现错误:-

$ sed "s/'100.45.9.147'/\\$(cat apiServer.txt)/g" checkNTP.sh $ sed“ s /'100.45.9.147'/ \\ $(cat apiServer.txt)/ g” checkNTP.sh

echo -e "\n"
apiServer=$(cat apiServer.txt)
usertoken=$(cat tokenfile.txt)
curl -k  -H "Authorization: Bearer ${usertoken}" -H 'Content-Type: application/json' "https://${apiServer}/configapi/v1/SystemSettingsNTP"

echo -e "\n\n"

$ sed -i "s/'100.45.9.147'/\\$(cat apiServer.txt)/g" checkNTP.sh $ sed -i“ s /'100.45.9.147'/ \\ $(cat apiServer.txt)/ g” checkNTP.sh

sed: 1: "checkNTP.sh": command c expects \ followed by text

Here is the content of checkNTP.sh 这是checkNTP.sh的内容

echo -e "\n"
apiServer='100.45.9.147'
usertoken=$(cat tokenfile.txt)
curl -k  -H "Authorization: Bearer ${usertoken}" -H 'Content-Type: application/json' "https://${apiServer}/configapi/SystemSettingsNTP"

echo -e "\n\n"

使用下面的-i ''开关解决了这种情况:

sed -i '' "s/'10.45.9.147'/\\\\$\\\\(cat apiServer.txt\\\\)/g" fileName.txt

This might work for you (GNU sed): 这可能对您有用(GNU sed):

sed 's/'\''100\.45\.9\.147'\''/$(cat apiServer.txt)/' file

Single quotes are best poked through quoted from the shell, this allows all other characters other than metacharacters to represent themselves and the metacharacters can be quoted as normal eg . 最好将单引号从外壳引号中戳出,这样可以使除元字符以外的所有其他字符都可以表示自己,并且可以将元字符引用为普通字符,例如. must be quoted \\. 必须加引号\\. otherwise it just represent a single character. 否则,它仅代表一个字符。

If you want a shell variable to replace text again poke a hole into the shell and surround the variable double quotes so as to allow for possible white space. 如果要让shell变量再次替换文本,请在shell中戳一个孔,并用双引号引起来,以留出可能的空白。 Also remember that should the variable contain metacharacters these should be quoted beforehand otherwise the substitution command might cause a sed syntax error. 还请记住,如果变量包含元字符,则应事先将其引号,否则替换命令可能会导致sed语法错误。 This usually happens when the variable has characters in it that clash with the substitution delimiters ie normally / 通常,当变量中包含与替换定界符冲突的字符时,即通常/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM