[英]modify a file using a bash script with sed
similar to these questions: 与这些问题类似:
In a file like this: 在这样的文件中:
define('_DB_NAME_', 'anything');
define('_DB_USER_', 'something else');
define('_DB_PASSWD_', 'and another value');
how to use sed to replace the value anything
, something
and another
(which are unknown) by refering to the key values _DB_NAME_
, _DB_USER_
and _DB_PASSWD
? 如何用sed来替换值
anything
, something
和another
由指的关键值(未知) _DB_NAME_
, _DB_USER_
和_DB_PASSWD
?
You probably want: 您可能想要:
sed -E "
s/('_DB_NAME_', ')[^']+/\1ABC/
s/('_DB_USER_', ')[^']+/\1DEF/
s/('_DB_PASSWD_', ')[^']+/\1GHI/
"
I think awk is more readable: 我认为awk更具可读性:
awk -F "'" -v OFS="'" '
$2 == "_DB_NAME_" {$4 = "ABC"}
$2 == "_DB_USER_" {$4 = "DEF"}
$2 == "_DB_PASSWD_" {$4 = "GHI"}
{print}
'
sed "s/\(define('_DB_NAME_', \).*/\1'new value');/" filename
and likewise for the other two. 其他两个也一样。
If you want to alter the file in place, you can use -i
, but you have to be careful, different versions of sed handle that differently. 如果要在适当的位置更改文件,可以使用
-i
,但必须小心,不同版本的sed的处理方式有所不同。
sed -i -e 's/anything/newanything/g;s/something/newthing/g;s/another/newanother/' tempfile
Where tempfile contains that code you had. tempfile包含您拥有的代码。 Output looks like this
输出看起来像这样
define('_DB_NAME_', 'newanything');
define('_DB_USER_', 'newthing else');
define('_DB_PASSWD_', 'and newanother value');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.