在文件 sip.conf 或任何基于文本的文件中的字符串“nat = no”之前添加一行“allow = alaw”

在文件 sip.conf 或任何基于文本的文件中的字符串“nat = no”之前添加一行“allow = alaw”

在文件 sip.conf 或任何基于文本的文件中的字符串“nat = no”之前添加一行“allow = alaw”。如果“allow = alaw”在“nat = no”之前已经存在,则不应添加它。

文件内容:

secret =
nat = no
progressinband = yes

allow = ulaw
allow = alaw
nat = no
progressinband = yes

disallow = all
allow = ulaw
nat = no
progressinband = yes

我的尝试:

awk '/nat = no/ { if(lastLine == "allow = alaw") { print } } { lastLine = $0 }' sip.conf

答案1

awk -v add="allow = alaw" '/^nat = no$/&&lastLine!=add{print add}{lastLine=$0}1' sip.conf
  • -v add="allow = alaw"将变量设置add为 awk。
  • /^nat = no$/&&lastLine!=add检查当前行是否正好是“nat = no”,如果最后一行不是我们要添加的行,则检查“allow = alaw”。如果属实,
    • {print add}打印要添加的行。
  • {lastLine=$0}保存当前行值,仅在下一个循环中使用。
  • 1打印当前行。

举一个最小的例子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

相关内容