Shell-Script
在文件 sip.conf 或任何基於文本的文件中的字元串“nat = no”之前添加一行“allow = alaw”
在文件 sip.conf 或任何基於文本的文件中,在字元串“nat = no”之前添加一行“allow = alaw”。如果在“nat = no”之前已經存在“allow = alaw”,則不應添加。
文件內容:
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
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