开发者

sed circular replacements

In my file input.txt, I want to replace A->B, B->C, and C->A i.e. I want to run

s/A/B/g;
s/B/C/g;
s/C/A/g;

However, I don开发者_运维知识库't want the patterns to operate on the new text i.e. if I run the above sed script, A becomes unchanged A->B->C->A, and B goes to A (B->C->A)

Is there a way to do the replacements I want?

Thanks


There might be a better way, but if there are suitable X and Y not in your input.txt you could try:

s/A/X/g;
s/B/Y/g;
s/C/A/g;
s/X/B/g;
s/Y/C/g;


I'd use tr : tr 'ABC' 'BCA'


Use the y operator instead of the s operator:

sed y/ABC/BCA/ 


We can complement the good bgg answer this way. Just append a newline to the strings to be used as X or Y. If we have this file:

$ cat teste.in 
ABC DEF GHI
GHI ABC DEE
DEF ABB ABCd

We execute this sed command:

$ sed 's/ABC/ABC\n/g 
s/DEF/DEF\n/g
s/GHI/ABC/g
s/ABC\n/DEF/g
s/DEF\n/GHI/g' teste.in
DEF GHI ABC
ABC DEF DEE
GHI ABB DEFd

Since it is very unlikely that a newline will appear in a line, it works. (Note that I used GNU sed. Some seds cannot accept the \n notation. In this case, just use a backslash followed by an actual newline:

$ sed 's/ABC/ABC\
/g 
s/DEF/DEF\
/g
s/GHI/ABC/g
s/ABC\
/DEF/g
s/DEF\
/GHI/g' teste.in
DEF GHI ABC
ABC DEF DEE

This should work.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜