我有一个字符串:
'driver' => 'Cake\Database\Driver\Mysql'
我需要替换为:
'foo' => 'bar'
但我的sed命令似乎都没有,例如
sed -i "s/\x27driver\x27 => \x27Cake\Database\Driver\Mysql\x27/\x27driver\x27 => \x27Cake\Database\Driver\Postgres\x27/g" /path/to/file.ext
或
sed -i "s/'driver' => 'Cake\Database\Driver\Mysql'/'driver' => 'Cake\Database\Driver\Postgres'/g" /path/to/file.ext
我该如何替换?
谢谢!
答案 0 :(得分:1)
您可以使用:
SQ=$'\x27'
sed "s/${SQ}driver${SQ} => ${SQ}Cake\\\\Database\\\\Driver\\\\Mysql${SQ}/${SQ}driver${SQ} => ${SQ}Cake\\\\Database\\\\Driver\\\\Postgres${SQ}/" file
'driver' => 'Cake\Database\Driver\Postgres'
您需要使用\\\\
来匹配\
并匹配单引号定义变量,如上所示。
答案 1 :(得分:1)
这适用于我使用GNU sed,我不知道为什么它不可移植:
$ path='Cake\\Database\\Driver\\Mysql'
$ sed "s/'driver' => '${path}'/'foo' => 'bar'/" <<<"'driver' => 'Cake\\Database\\Driver\\Mysql'"
'foo' => 'bar'
在双引号内,单引号可以按字面意思使用。为了使sed行更容易,我将路径移动到变量。
答案 2 :(得分:0)
这可以在这里进行快速测试:
sed "s/'driver' => 'Cake\\\Database\\\Driver\\\Mysql'/'driver' => 'Cake\\\Database\\\Driver\\\Postgres'/g"
答案 3 :(得分:0)
你必须逃避反斜杠:\
:
kent$ sed "s#'driver' => 'Cake\\\\Database\\\\Driver\\\\Mysql'#'foo' => 'bar'#"<<<"'driver' => 'Cake\Database\Driver\Mysql'"
'foo' => 'bar'
kent$ sed 's/\x27driver\x27 => \x27Cake\\Database\\Driver\\Mysql\x27/\x27foo\x27 => \x27bar\x27/'<<<"'driver' => 'Cake\Database\Driver\Mysql'"
'foo' => 'bar'
答案 4 :(得分:0)
不是Linux人,只是在这里猜测。
Perl引擎处理器应该看到什么:
s/'driver' => 'Cake\\Database\\Driver\\Mysql'/'driver' => 'Cake\\Database\\Driver\\Postgres'/g
命令处理器的单引号:
sed 's/\'driver\' => \'Cake\\\Database\\\Driver\\\Mysql\'/\'driver\' => \'Cake\\\Database\\\Driver\\\Postgres\'/g' /path/to/file.ext
命令处理器的双引号:
sed "s/'driver' => 'Cake\\\\Database\\\\Driver\\\\Mysql'/'driver' => 'Cake\\\\Database\\\\Driver\\\\Postgres'/g" /path/to/file.ext
答案 5 :(得分:0)
所给出的答案都没有像我们写的那样对我有用,所以我用它们作为测试的灵感,发现这对我有用:
sed -i 's/\x27driver\x27 => \x27Cake\\\Database\\\Driver\\\Postgres\x27/\x27driver\x27 => \x27Cake\\\Database\\\Driver\\\Mysql\x27/g' /path/to/file.ext
sed -i 's/\x27driver\x27 => \x27Cake\\\Database\\\Driver\\\Mysql\x27/\x27driver\x27 => \x27Cake\\\Database\\\Driver\\\Postgres\x27/g' /path/to/file.ext
或者,对于foo-bar示例:
sed -i 's/\x27driver\x27 => \x27Cake\\\Database\\\Driver\\\Mysql\x27/\x27foo\x27 => \x27barx27/g' /path/to/file.ext
谢谢大家,特别是@Kent和@anubhava