0

I am creating a script to populate an htaccess file with a blacklist. To do this I have used curl to download a blacklist, which I read into an array using a while statement, that way I can disregard lines that don't begin with 'deny'. Now I want to insert the elements from the array into the .htaccess file.

The array is called DENY_DATA and contains entries that look like this:

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

I have inserted two lines into the .htaccess file between which I want the deny statements to go. They look like this:

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

I have tried the following using awk. However, this results in the tmp file containing only ${DENY_DATA[@]} as a string.

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

I have also tried with sed as per Inserting multiline text from file to another file after pattern and Bash script to insert code from one file at a specific location in another file?. With this, I am left with the original htaccess file but no deny statements.

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

Is there a simple fix, or is there a better way to approach this?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Adam
  • 94
  • 1
  • 12

1 Answers1

2

You can keep the deny data in a file instead of reading it into an array, and then append the file after the blacklist start line with sed's r (read file) command:

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

where denydata contains the deny statements.

If you have the data nowhere else but in the array, you can write it to a file first:

printf '%s\n' "${DENY_DATA[@]}" > denydata
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
  • Thats great, did the job. Thanks – Adam Sep 04 '19 at 19:09
  • Is it possible to turn denydata into a variable so that I don't have to statically write the file location? – Adam Sep 04 '19 at 19:30
  • 1
    @Adam If you double quote the sed command, you can use shell variables; for example, assuming `$name` contains the name of the file you want, you can use `sed "/#~~~~~~~~~ BLACKLIST START ~~~~~~~~~~/r $fname" .htaccess`. – Benjamin W. Sep 04 '19 at 19:56