I want to add two line
allow = alaw
allow = g729
before a string
nat = no
in a file sip.conf
(or any text based file). If allow = alaw
and allow = g729
already exists before nat = no
it should not be added. This script will run every hour.
And the line should not be added in the two sections immediately after [general]
and [providertrunk0]
of the file.
Example file content:
[general]
disallow = all
allow = ulaw
nat = no
[providertrunk0]
disallow = all
allow = ulaw
;allow = alaw
nat = no
secret =
nat = no
progressinband = yes
allow = ulaw
allow = alaw
nat = no
progressinband = yes
disallow = all
allow = ulaw
allow = g729
nat = no
progressinband = yes
expected output
[general]
disallow = all
allow = ulaw
nat = no
[providertrunk0]
disallow = all
allow = ulaw
;allow = alaw
nat = no
secret =
allow = alaw
allow = g729
nat = no
progressinband = yes
allow = ulaw
allow = alaw
allow = g729
nat = no
progressinband = yes
disallow = all
allow = ulaw
allow = alaw
allow = g729
nat = no
progressinband = yes
My attempt
cat addCodec.awk
BEGIN {
RS=""; ORS="\n\n"; FS=OFS="\n"
skip["[general]"]
skip["[providertrunk0]"]
addCodec = "allow = alaw\nallow = g729"
tgt = "nat = no"
}
!($1 in skip) {
for (i=1; i<NF; i++) {
if ( ($i != addCodec) && ($(i+1) == tgt) ) {
$i = $i OFS addCodec
}
}
}
{ print }
awk -f addCodec.awk sip.conf
this script works if both line does not exist , it will add them. If a single line exist then I am stuck , what if condition I need to use.
awk
but as I understand$i
gives single line but you compare it with string which has two lines"allow = alaw\nallow = g729"
- so it can't be correct. And maybe you should check separatelly$i == tgt && $(i-1) == "allow = g729"
and later$i == tgt && $(i-2) == "allow = alaw"
;allow = alaw
really supposed to be that in the[providertrunk0]
block or is the leading;
a mistake? If it is a mistake then please fix your example.allow = alaw
if;allow = alaw
is present we should ignore it? If;allow = alaw
is present in a block where we otherwise want to add it, should we remove or uncomment it or leave it or what?allow = alaw
andallow = g729
exist in the block but there's another line between them andnat = no
? What if they exist but there's another line between them? What if they exist afternat = no
but in the same block. Please edit your question to describe how all the different cases should be handled or state if they can't occur, and make sure your sample input/output covers all possible cases.