我正在编写一个脚本来尝试加速我的基本Wordpress安装。它下载最新版本,解压缩,更改客户端名称,然后更新配置文件中的一些文本。
但是我无法使用sed插入包含特殊字符的多行。多行来自WP密钥生成器https://api.wordpress.org/secret-key/1.1/salt/,它们将替换标准
define('AUTH_KEY', 'put your unique phrase here');
define('SECURE_AUTH_KEY', 'put your unique phrase here');
define('LOGGED_IN_KEY', 'put your unique phrase here');
等...
以下是给我一个问题的代码
# Download data to variable
salt="`curl https://api.wordpress.org/secret-key/1.1/salt/`"
sed -i "/NONCE_SALT/a $salt" $pname/wp-config-sample.php
我正在将生成的文本下载到变量中,然后在新行上插入标准文本中的最后一个实例后插入(我稍后会删除所有这些标准行)。它会引发错误;
"ed: -e expression #1, char 112: extra characters after command"
当我输入一行标准文本时,它很好。如果我在$salt
周围添加引号,则只在文件中打印文字$salt
。
是否是插入此数据的正确方法?请记住,我需要在文件中的特定点后插入?
任何提示或提示都非常受欢迎。这是我第一次尝试使用bash脚本。
答案 0 :(得分:4)
a
函数要求在字符串中的任何内部换行符之前加上反斜杠。因此,一种方法是使用sed
添加必要的反斜杠:
# Download data to variable, adding \ to all but the last line:
salt="$(curl https://api.wordpress.org/secret-key/1.1/salt/ | sed '$ ! s/$/\\/')"
sed -i "/NONCE_SALT/a $salt" "$pname/wp-config-sample.php"
(请注意,我使用的是$(...)
而不是`...`
:后者的引用规则很痛苦。在这种情况下,我不得不写\\\\
而不是\\
。)
那就是说,在这种情况下,我认为将salt-stuff保存到临时文件可能更简单,并使用r
代替a
:
# Download data to the file salt.txt:
curl https://api.wordpress.org/secret-key/1.1/salt/ > salt.txt
sed -i "/NONCE_SALT/r salt.txt" "$pname/wp-config-sample.php"
rm salt.txt # could also be done in a trap
答案 1 :(得分:2)
试试这个:
awk -v salt="$(curl https://api.wordpress.org/secret-key/1.1/salt/)" '
{print} /NONCE_SALT/{print salt}
' "$pname/wp-config-sample.php" > tmp$$ && mv tmp$$ "$pname/wp-config-sample.php"
与sed不同,awk不受后退或引号或换行符的影响,不会导致sed失败。
答案 2 :(得分:1)
不是通过将wp-config.php
的内容替换为文件$salt
来形成文件wp-config-sample.php
,而是编写wp-config-sample.php,使用{更简单明了{1}}从egrep -v
中删除行,然后在最后连接必要的新行。也就是说,创建一个脚本来执行以下三个步骤,并使用适当的代码替换wp-config-sample.php
:
write-customer-stuff
您还可以为基本错误检查添加如下所示的行:
egrep -v 'name_here|word_here|unique phrase here' wp-config-sample.php > wp-config.php
write-customer-stuff >> wp-config.php
curl https://api.wordpress.org/secret-key/1.1/salt/ >> wp-config.php