awk -v add="allow = alaw" '/^nat = no$/&&lastLine!=add{print add}{lastLine=$0}1' sip.conf
-v add="allow = alaw"
sets an variable add
to awk.
/^nat = no$/&&lastLine!=add
checks if current line is exactly "nat = no" and if the last line is not the line we want to add, "allow = alaw". If true,
{print add}
prints the line to be added.
{lastLine=$0}
saves the current line value, only in the next cycle it will be used.
1
prints the current line.
On a minimal example sip.conf
:
secret =
nat = no
progressinband = yes
allow = ulaw
allow = alaw
nat = no
progressinband = yes
disallow = all
allow = ulaw
nat = no
progressinband = yes
$ awk -v add="allow = alaw" '/^nat = no$/&&lastLine!=add{print add}{lastLine=$0}1' sip.conf > out
$ mv out sip.conf
$ cat sip.conf
secret =
allow = alaw
nat = no
progressinband = yes
allow = ulaw
allow = alaw
nat = no
progressinband = yes
disallow = all
allow = ulaw
allow = alaw
nat = no
progressinband = yes