Add line to configuration file from a bash script?
Solution 1
awk
can be used for this. The bellow script will only add text after finding a <Location />
tag.
awk '/\<Location \/\>/{ start=1 } {if(start) ++start; if(start==4) print " Allow all"} 1' infile
For the the bellow input file:
stuff
<Location />
Order allow,deny
</Location>
more
stuff
This script produces:
stuff
<Location />
Order allow,deny
Allow all
</Location>
more
stuff
If you want to replace several sections like this, the same script can be easily adapted:
awk '/\<Location \/\>/{ start=1 } {if(start) ++start; if(start==4){print " Allow all"; start=0}} 1' infile
Solution 2
sed '/Order allow,deny/ aAllow all' < yourFile
This will output the modified file to stdout. If you want to modify it in place then (sed(1)):
-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if SUFFIX supplied)
Explanation:
For each line that matches `/Order allow,deny/`:
Execute command 'a' (append) with 'Allow all' as parameter
http://grymoire.com/Unix/sed.html is an excellent resource to learn more about sed
.
Solution 3
If you just blindly want to add the Allow all
statement after any Order allow,deny
then the following sed
will work
sed -i 's/Order\ allow,deny/Order\ allow,deny\nAllow\ all/' <inputfilename>
Related videos on Youtube
tkrn
Updated on September 18, 2022Comments
-
tkrn over 1 year
I am trying to figure out to locate a line in a configuration file, then to drop down two lines then to insert a line of code. I was attempting to do this in awk/sed but got stuck on the carriage return. I not tied to awk/sed but looking for a clean way to accomplish this.
<Location /> Order allow,deny </Location>
Then to add a line into that block:
<Location /> Order allow,deny Allow all </Location>
-
terdon over 8 yearsPlease edit your question and add more details. Is what you're showing the entire configuration file? Can there be more than one
</Location>
in your file? More than oneOrder allow,deny
? If yes, how can we know which one is your target? -
Kira over 8 yearsYou want to do this more than once?
-