skip to Main Content

I need to replace a keyword with another keyword/string in a Linux file. i.e

IfModule mod_dir.c>
DirectoryIndex index.html index.cgi index.pl index.php index.xhtml 
index.htm
</IfModule>

Here I want to replace or swap index.html to index.php in 2nd line or I want to prioritize index.php in place of index.html and put index.html inplace of index.php.

I have to do the above mentioned task via a shell script and for that I have already tried the command:

awk 'NR==2 { t = $2; $2 = $5; $5 = t; print; } ' abc.txt

But it is not saving in the file i.e abc.txt in which I want to change the content.

Please let me know what am I doing wrong.

3

Answers


  1. For any command cmd, to update the original file:

    cmd file > tmp && mv tmp file
    

    If you’re using GNU awk you could instead use awk -i inplace '...' file and it’ll do the above for you internally, just like sed -i and perl -i, etc. do.

    Login or Signup to reply.
  2. You can do that with just sed:

     sed -i.bak 's/index.html/index.php/g' abc.txt
    

    That will replace ALL ocurrences of index.html with index.php in abc.txt and will save a copy of abc.txt original contents on abc.txt.bak.

    Login or Signup to reply.
  3. another option is with the below perl command :

    perl -pi -w -e 's/index.html/index.php/g;' abc.txt
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search