我有一个包含以下行的配置文件,想知道添加&#39 ;;'的方法。在[跑步机]之后的每一行的开头直到下一个空白行。我想从脚本中执行此操作,因为这些行将包含在内,具体取决于该环境的配置。
[treadmill]
type = aor
contact = server.domain.com
[A_SRV]
type = aor
contact = serverA.domain.com
[B_SRV]
type = aor
contact = serverB.domain.com
[treadmill]
type = identify
endpoint = treadmill
match = server.domain.com
[C_SRV_IDEN]
type = identify
endpoint = sip
match = server.domain.com
[treadmill]
type = endpoint
context = LocalSets
dtmf_mode = rfc4733
disallow = all
allow = ulaw
direct_media = no
aors = treadmill
答案 0 :(得分:1)
sed -e '/\[treadmill\]/,/^$/{//!s/^/;/}' treadmill.txt
说明:
/\[treadmill\]/,/^$/
使用/START/,/END/
语法在START到END系列行中的花括号{}
中应用后续命令,包括START和END行。 /^$/
需要一个完全空行,没有空格。
{//!s/^/;/}
是大括号中的一个命令,在上述范围内应用。
//!
表示“与上一场比赛不匹配”,因为//
是上一场比赛。这可以防止处理START和END行
//!s/^/;/
将替换s/^/;/
链接到//!
为真的行。这会在START和END之间的每一行添加一个分号
我对分号添加的初步建议是s/.*/;&/
- 这会将.*
替换为;&
,其中替换方&
对应于.*
匹配。正如@WilliamPursell评论的那样,这可能不如s/^/;/
!
是一个需要反斜杠转义的特殊字符。应该可以在bash中取消。<强>输出:强>
[treadmill]
;type = aor
;contact = server.domain.com
[A_SRV]
type = aor
contact = serverA.domain.com
[B_SRV]
type = aor
contact = serverB.domain.com
[treadmill]
;type = identify
;endpoint = treadmill
;match = server.domain.com
[C_SRV_IDEN]
type = identify
endpoint = sip
match = server.domain.com
[treadmill]
;type = endpoint
;context = LocalSets
;dtmf_mode = rfc4733
;disallow = all
;allow = ulaw
;direct_media = no
;aors = treadmill
答案 1 :(得分:0)
使用awk
awk '!NF { f = 0 }
{ print (f == 1 ? ";" : "") $0 }
$0 ~ /^\[treadmill\]$/
{ f = 1 }
' file
答案 2 :(得分:0)
这很复杂,但确实有效。
grep -ne "^\[treadmill\]" $DIRPATH/pjsip.conf.sample | cut -d : -f 1 | awk '{print $1" on"}' > lines.txt
grep -n '^$' $DIRPATH/pjsip.conf.sample | cut -d : -f 1 | awk '{print $1" off"}' >> lines.txt
cat lines.txt | sort -n > lines2.txt
IFS=$'\n' # make newlines the only separator
declare -i arr4
items=0
for i in $(cat lines2.txt) ; do
SWITCH=`echo $i | cut -d' ' -f 2`
LINE=`echo $i | cut -d' ' -f 1`
if [ "$SWITCH" = "on" ] && [ $SWITCHED -eq 0 ]; then
SWITCHED=1
arr4[$items]=$LINE
((++items))
fi
if [ "$SWITCH" = "off" ] && [ $SWITCHED -eq 1 ]; then
SWITCHED=0
arr4[$items]=$LINE
((++items))
fi
done
count=${#arr4[@]}
let SECTIONS=$count/2
let SECTIONS-=1
for i in `seq 0 $SECTIONS` ; do
let START=$((arr4[$i*2]))
let END=$((arr4[($i*2)+1]))-1
for j in `seq ${START} ${END}` ; do
sed -i "$j s/^/;/" $DIRPATH/pjsip.conf.sample
done
done
rm lines.txt lines2.txt