Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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

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

I need to replace 45.152.35.2 with my current IP. But 45.152.35.2 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 (75.152.35.4) 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    75.152.35.4      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?

share|improve this question

1 Answer 1

You can use this:

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

Explanation:

  • 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
share|improve this answer
    
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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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