I have a file (.htaccess) which contains below excerpt.

<Files wp-login.php>
order deny,allow
deny from all
allow from

I need to replace with my current IP. But is not static. I need to find the IP expression at allow from line and replace it with my current IP.

I also need to get my current IP ( from w command:

12:13:07 up 21 days,  3:01,  1 user,  load average: 0.18, 0.13, 0.12
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/0      14:29    0.00s  0.10s  0.00s w

How can I get current IP from w command and replace allow from line in .htaccess file?


You can use this:

sed -i "s/allow from [0-9,\.]*/allow from $(w -h | awk '{print $3}' | head -1)/g" .htaccess


  • sed -i "s/.../$(...)/g .htaccess: replaces the allow from line with
  • w -h | awk '{print $3}' | head -1: the frist line of the output of w
  • I saw which is why I deleted my comment and instead upvoted :). You could also use sed -i -r "s/(allow from )[0-9\.]*/\1 $(w | awk '($NF=="w"){print $3}')/" .htaccess which has the added benefit of ensuring the right IP even if w returns multiple lines and multiple users. – terdon Sep 24 '14 at 22:09
  • @chaos works great but I want to change allow from line only for wp-login.php section. .htaccess file may contain many allow from lines. Your code replaces globally. How can it be done to change allow from line in wp-login.php section only? – NecNecco Sep 24 '14 at 22:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.