0

I'm trying to make it easier for me to keep my url shortener less spammy. When I have to go in through ssh and keep adding another line to my .htaccess it gets really tedious and annoying really fast. So I was wondering if there was a way to add a line of text easily and that could be put in a script

Example:

<Directives here>
Order Deny,Allow
Deny from 255.255.255.255
Deny from 0.0.0.0
Deny from 1.2.3.4
<Other Directives here as well as ending Directive>

Now lets say for giggles I wanted to add 127.0.0.1 and 192.168.0.1 to this, but since I can't directly echo where I want it, how would I go about this. Bash or Python answers accepted

IotaSpencer
  • 77
  • 10

3 Answers3

0

sed is probably the easiest to use and almost everywhere available. The following will insert a line before the last one:

sed -e '$i Deny from 192.168.0.1' .htaccess

This works assuming you want to insert before the last line. Having read your question a second time I noticed you wrote "<Other Directives here...>". Although this is a bit of a hidden hint, I assume you want to insert a line to the first section into content like this:

<Directive_1>
Order Deny,Allow
Deny from 255.255.255.255
Deny from 0.0.0.0
Deny from 1.2.3.4
</Directive_1>
...
<Directive_n>
...
</Directive_n>

The following sed command will insert a line just before the closing tag of the first section:

sed -e '/^<\/Directive_1>$/i Deny from 192.168.0.1' .htaccess

insecure
  • 552
  • 4
  • 10
  • 1
    By adding the `-i` option, the existing `.htaccess` file can be changed in place: `sed -i -e '$i Deny from 192.168.0.1' .htaccess` – John1024 Jan 26 '14 at 20:22
0

Here's another way, in sh/ksh/bash: http://stromberg.dnsalias.org/~strombrg/contextual

dstromberg
  • 6,954
  • 1
  • 26
  • 27
0

Using a combination of head, echo and tail, you can create a temporary file with the required lines, and then mv or cp over the original file.

Add Deny from 127.0.0.1 to your example .htaccess:

(head -n -1 .htaccess
 echo 'Deny from 127.0.0.1'
 tail -n 1 .htaccess) > .htaccess.tmp
mv -b .htaccess.tmp .htaccess

# cat .htaccess
<Directives here>
Order Deny,Allow
Deny from 255.255.255.255
Deny from 0.0.0.0
Deny from 1.2.3.4
Deny from 127.0.0.1
<Other Directives here as well as ending Directive>

head -n -1: get all original lines except the last, echo the new line, tail -n 1: get last original line. () > writes everything to temporary file. mv -b overwrites the original, saving a backup.

This solution of course assumes you know how many lines from the end of file you want to add your new content.

grebneke
  • 4,414
  • 17
  • 24