【问题标题】:Using bash to insert data from array into file at specific location使用 bash 将数组中的数据插入到特定位置的文件中
【发布时间】:2019-09-05 02:52:45
【问题描述】:

我正在创建一个脚本来使用黑名单填充 htaccess 文件。为此,我使用 curl 下载了一个黑名单,我使用 while 语句将其读入数组,这样我就可以忽略不以“拒绝”开头的行。现在我想将数组中的元素插入到.htaccess 文件中。

该数组名为DENY_DATA,包含如下所示的条目:

deny from 64.62.252.163
deny from 167.99.255.132
deny from 27.209.94.238
deny from 64.188.8.229
...

我已经在.htaccess 文件中插入了两行,我希望拒绝语句在它们之间。它们看起来像这样:

#~~~~~~~~~ BLACKLIST START ~~~~~~~~~~
#********* BLACKLIST END **********

我使用 awk 尝试过以下操作。但是,这会导致 tmp 文件仅包含 ${DENY_DATA[@]} 作为字符串。

awk '/^#~~~~~~~~~/ { printf "%s\n", "${DENY_DATA[@]}" }' .htaccess > tmp.file

我也按照Inserting multiline text from file to another file after patternBash script to insert code from one file at a specific location in another file? 尝试过使用sed。有了这个,我留下了原始的 htaccess 文件,但没有拒绝声明。

sed -e '/^#~~~~~~~~~/r printf "%s\n" "${DENY_DATA[@]}"' .htaccess > tmp.file

有没有简单的解决方法,或者有更好的方法来解决这个问题?

【问题讨论】:

    标签: bash .htaccess awk sed


    【解决方案1】:

    您可以将拒绝数据保存在文件中而不是将其读取到数组中,然后使用 sed 的r(读取文件)命令将文件附加到黑名单开始行之后:

    sed '/#~~~~~~~~~ BLACKLIST START ~~~~~~~~~~/r denydata' .htaccess
    

    其中denydata 包含拒绝语句。

    如果你在数组中没有其他地方的数据,你可以先将它写入一个文件:

    printf '%s\n' "${DENY_DATA[@]}" > denydata
    

    【讨论】:

    • 太好了,完成了。谢谢
    • 是否可以将denydata转为变量,这样我就不用静态写入文件位置了?
    • @Adam 如果双引号 sed 命令,可以使用 shell 变量;例如,假设$name包含你想要的文件名,你可以使用sed "/#~~~~~~~~~ BLACKLIST START ~~~~~~~~~~/r $fname" .htaccess
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 2015-12-25
    • 2021-05-01
    • 2013-10-10
    相关资源
    最近更新 更多