bash sed 单引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8510713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sed single quotes
提问by Chasester
I've been banging into escaping single quote's problem using SED (Bash shell).
我一直在努力使用 SED(Bash shell)来逃避单引号的问题。
I need to make
我需要做
$cfg['Servers'][$i]['password'] = '';
into
进入
$cfg['Servers'][$i]['password'] = 'mypassword';
What I've tried is:
我试过的是:
sed -i "s/$cfg['Servers'][$i]['password'] = '';/$cfg['Servers'][$i]['password'] = '$rootpassword';/g" /usr/share/phpmyadmin/libraries/config.default.bak
Which ends up really jumbling the line.
这最终真的使线路混乱。
$cfg['Servers'][$i]['password['Servers'][]['passsword'] = 'mypassword'
I've tried the '\'' to escape single quotes and I think everything else under the sun but just can't get it quite there.
我已经尝试使用 '\'' 来转义单引号,我认为其他一切都在阳光下,但无法完全实现。
can anyone point to my probable obvious mistake?
谁能指出我可能的明显错误?
Thank you.
谢谢你。
回答by Kent
instead of escaping, you can use \x27for single quote. this works not only for sed, for awk etc. as well.
您可以使用\x27单引号代替转义。这不仅适用于 sed,也适用于 awk 等。
see test:
见测试:
kent$ cat tt
$cfg['Servers'][$i]['password'] = ''
kent$ sed -r 's/($cfg\[\x27Servers\x27\]\[$i\]\[\x27password\x27\] \= \x27)\x27/mypassword\x27/g' tt
$cfg['Servers'][$i]['password'] = 'mypassword'
note that, the sed line may not be the best solution for your problem, e.g. put the whole string to "s/../" may not be necessary. However, I just want to show how the \x27 worked.
请注意, sed 行可能不是您问题的最佳解决方案,例如,可能不需要将整个字符串放在 "s/../" 中。但是,我只想展示 \x27 是如何工作的。
回答by jcollado
$ sed -i "s/$cfg\['Servers'\]\[$i\]\['password'\] = '';/$cfg['Servers'][$i]['password'] = '$rootpassword';/g" file
回答by c00kiemon5ter
Try this:
尝试这个:
sed -i "/Servers.*password.*''$/s/''/'foo'/" /path/to/your/testfile
Match a line that contains "anything..Servers..anything..password..anything..''" (end with '') and on that line replace ''with 'foo'
匹配包含“anything..Servers..anything..password..anything..''”(以 结尾'')的行'',并在该行替换为'foo'
This can match more than one lines, but only the firstoccurance will be changed.
Test it, it's most probable that .. Servers .. password .. ''is only on one line.
这可以匹配多行,但只会更改第一次出现。测试一下,很有可能.. Servers .. password .. ''只有一行。
Or you can just escape everything.
或者你可以逃避一切。

