将文本附加到特定文件夹下的所有文件

Append a text to all files under specific folder

我需要将文件底部的文本附加到我所有客户网站的 /home 目录下的 .htaccess 文件中。

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}`

我已经尝试 echo 'code' >> .htaccess 但失败了,因为它包含新行,我也尝试过 \n\r 但没有成功,我正在使用 printf ;我可以添加新行,但它说

bash: printf: `}': invalid format character

更新..

我按照 tripleee 代码成功修复了无效的格式字符,但不幸的是它没有附加我所有的 .htaccess 文件

这是代码

for file in /home/*/public_html/.htaccess; do
    printf '%s\n' '# Redirect to https' \
        'RewriteEngine On' \
        'RewriteCond %{HTTPS} off' \
        'RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}' >>".htaccess"
done

我可以使用这些代码解决问题

printf '%s\n' '# Redirect to https' \
        'RewriteEngine On' \
        'RewriteCond %{HTTPS} off' \
        'RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}'  |
tee -a /home/*/public_html/.htaccess

感谢 tripleee

您需要加倍 % 以在 printf 格式字符串中生成文字百分比字符。或者,将显式格式字符串传递给 printf 并将各行作为参数传递。

printf '%s\n' 'RewriteEngine On' \
        'RewriteCond %{HTTPS} off' \
        'RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}' |
tee -a /home/*/public_html/.htaccess >/dev/null

你没有理由不能也使用 echo,虽然它对眼睛有点刺激。

echo 'RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}' |
tee -a /home/*/public_html/.htaccess >/dev/null

您可以使用 echo -e 获得类似的东西,但它不如 printf 便携和优雅。

您也可以简单地使用此处的文档:

tee -a /home/*/public_html/.htaccess<<-'____HERE' >/dev/null
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
____HERE

在 here-document 分隔符前加上破折号(减号)允许您使用制表符(但不是空格!)进行缩进;前导标签将从文本中删除。在分隔符周围加上引号会导致 shell 引用文档(即不会计算文档中的美元符号或反引号)。