使用 sed 一次搜索/替换不同的字符串

v0i*_*ess 2 sed

我正在使用 sed 在 php 文件中查找配置指令。从本质上讲,我需要设置字符串database_name_here,username_here并password_here与在config-sample.php相应的值(和文件重命名为config.php文件)。我当前的解决方案使用 sed 3 次,将输出重定向到临时文件。

sed -e 's/database_name_here/foo/g' config-sample.php > /tmp/config.1
sed -e 's/username_here/bar/g' /tmp/config.1 > /tmp/config.2
sed -e 's/password_here/bat/g' /tmp/config.2 > config.php
Run Code Online (Sandbox Code Playgroud)

我想知道如何在不必创建两个临时文件的情况下获得相同的结果?

Gil*_*il' 5

您可以将多个-e参数传递给 sed。在每一行上,依次应用每个转换。

<config-sample.php sed -e 's/database_name_here/foo/g' -e 's/username_here/bar/g' -e 's/password_here/bat/g' >config.php
Run Code Online (Sandbox Code Playgroud)

某些实现还允许您使用 a 分隔多个命令;,但情况并非总是如此,并且不适用于需要终止换行符的命令。大多数(但仍然不是全部)实现允许您使用换行符分隔多个命令。

请注意,如果您需要多个命令,则不需要使用临时文件,您可以使用管道。

<config-sample.php sed -e '…' | grep -v '^#' >config-without-comments.php
Run Code Online (Sandbox Code Playgroud)