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
For any command
cmd
, to update the original 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 likesed -i
andperl -i
, etc. do.You can do that with just
sed
:That will replace ALL ocurrences of
index.html
withindex.php
inabc.txt
and will save a copy ofabc.txt
original contents onabc.txt.bak
.another option is with the below perl command :