1

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>
2
  • Please 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 one Order allow,deny? If yes, how can we know which one is your target? Commented Jan 6, 2016 at 19:02
  • You want to do this more than once? Commented Jan 6, 2016 at 19:06

4 Answers 4

3
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.

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
1

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>
0

You can use Vim in Ex mode:

ex -sc '/Order allow,deny/a|Allow all' -cx file
  1. a append text and newline

  2. x save and close

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.