用sed代替;和空白

时间:2014-05-05 15:58:29

标签: bash ubuntu sed command spaces

我需要用sed命令替换这行:

;[homes]
;   browseable = no

在这一行:

[homes]
browseable = yes

4 个答案:

答案 0 :(得分:2)

sed -e 's/^; *//',除非您的示例不涵盖所有情况。

答案 1 :(得分:2)

有很多方法可以修复显示的两条线。如果您认为这是ini文件格式并且可能有其他部分包含browseable以及除[homes]之外的其他部分(不应编辑),则会变得有点棘手。

sed -e '/^;\[homes]/,/^;*\[/{
        s/;\[homes]/[homes]/
        s/^; *browseable.*/browseable = yes/
        }'

给定输入文件:

;[alerts]
;  browseable = no
;[homes]
;  browseable = no
;  alternatives = no
;[houses]
;  browseable = no
[mezzanine]
;  browseable = no
   alternatives = yes

上述脚本的输出是:

;[alerts]
;  browseable = no
[homes]
browseable = yes
;  alternatives = no
;[houses]
;  browseable = no
[mezzanine]
;  browseable = no
   alternatives = yes

答案 2 :(得分:1)

您可以使用awk进行更改。

awk '{sub(/^;[ ]*/,"")} /browseable/ {$3="yes"}1'
[homes]
browseable = yes

鉴于Jonthan的数据

awk '/homes/ {sub(/^;[ ]*/,"");f=1} f && /browseable/ {sub(/^;[ ]*/,"");$3="yes";f=0}1' file
;[alerts]
;  browseable = no
[homes]
browseable = yes
;  alternatives = no
;[houses]
;  browseable = no
[mezzanine]
;  browseable = no
   alternatives = yes

或者像这样:

awk '/homes/ {$0="[homes]";f=1} f && /browseable/ {$0="browseable = yes";f=0}1' file

答案 3 :(得分:0)

这也可以,

sed 's/^;//g;s/^ *\(.*\)/\1/g;s/no/yes/g' file