2015-12-07 144 views
0

我需要更换用括号百分号,例如包围文本百分号:用sed来替换括号

此%是%A%测试%

应该成为

这是{}为{测试}

我尝试:SED的/ \%([^]] *)\%/ {\ 1}/G”

但是,这导致:

这{是%A%测试}

+1

在排除类错误的字符:'[^] *' - >'[^%] *'。 –

回答

1

试试这个:

$ echo "This %is% a %test%" | sed -e 's/%\([^%]*\)%/{\1}/g' 
This {is} a {test} 
  • 你需要躲避组:\(...\)(否则你得到invalid reference \1 on 's' command's RHS
  • 使用[^%]*以匹配任何内容,但%
  • 您不需要转义%(但它也适用于\%)。
1

我会建议使用awk代替:

s='This %is% a %test%' 
awk -F'%' '{for (i=1; i<NF; i++) p = p $i (i%2 ? "{" : "}"); print p $NF}' <<< "$s" 
This {is} a {test} 
+0

在这种情况下,我更喜欢perl:'echo ... | perl -ne's /%(。*?)%/ {\ 1}/g; print'' ;-) – Kenney