桑达。如何更改特定模式旁边的行

时间:2011-12-01 05:15:10

标签: bash sed

我的档案是:

DIVIDER  
Sometext_string

many  
lines  
of random  
text  
DIVIDER  
Another_Sometext_string  
many  
many  
lines  
DIVIDER  
Third_sometext_string  
....

如何更改DIVIDER模式后面的行

结果必须是:

DIVIDER  
[begin]Sometext_string[end]

many 
lines  
of random  
text  
DIVIDER  
[begin]Another_Sometext_string[end]

many  
many  
lines  
DIVIDER  
[begin]Third_sometext_string[end]

....

1 个答案:

答案 0 :(得分:7)

可能会有所帮助 -

sed '/DIVIDER/{n;s/.*/[begin]&[end]\n/;}' file1

<强>执行:

[jaypal:~/Temp] cat file1
DIVIDER
Sometext_string

many
lines
of random
text
DIVIDER
Another_Sometext_string
many
many
lines
DIVIDER
Third_sometext_string

[jaypal:~/Temp] sed '/DIVIDER/{n;s/.*/[begin]&[end]\n/;}' file1
DIVIDER
[begin]Sometext_string[end]


many
lines
of random
text
DIVIDER
[begin]Another_Sometext_string[end]

many
many
lines
DIVIDER
[begin]Third_sometext_string[end]

<强>更新

此版本将在第一个DIVIDER之后处理一个空白行。

[jaypal:~/Temp] sed -e '0,/DIVIDER/{n;s/.*/[begin]&[end]/;}' -e '/DIVIDER/{n;s/.*/[begin]&[end]\n/;}' file1
DIVIDER
[begin]Sometext_string[end]

many
lines
of random
text
DIVIDER
[begin]Another_Sometext_string[end]

many
many
lines
DIVIDER
[begin]Third_sometext_string[end]

[jaypal:~/Temp] 

更新2:

现在没有其他问题,所以如果您愿意,我认为我会提供替代awk解决方案? :)

awk '/DIVIDER/{print;getline;sub(/.*/,"[begin]&[end]");print;next}1' file1

[jaypal:~/Temp] awk '/DIVIDER/{print;getline;sub(/.*/,"[begin]&[end]\n");print;next}1' file1
DIVIDER
[begin]Sometext_string[end]


many
lines
of random
text
DIVIDER
[begin]Another_Sometext_string[end]

many
many
lines
DIVIDER
[begin]Third_sometext_string[end]

[jaypal:~/Temp] 

这是为了处理DIVIDER之后的第一个空行 -

[jaypal:~/Temp] awk '/DIVIDER/{count++;print;getline;if(count==1) sub(/.*/,"[begin]&[end]");else sub(/.*/,"[begin]&[end]\n");print;next}1' file1
DIVIDER
[begin]Sometext_string[end]

many
lines
of random
text
DIVIDER
[begin]Another_Sometext_string[end]

many
many
lines
DIVIDER
[begin]Third_sometext_string[end]

[jaypal:~/Temp]