[英]replace string in pattern using shell command: sed, awk
Say I have a text file like this: 说我有一个像这样的文本文件:
a;bc;d;{a;b;cd}
ab;cde;f;{ab;c;defg}
ab;{a;b;cd};cde;f
...
and I want to replace all the semicolons in curly brackets by comma. 我想用逗号替换花括号中的所有分号。 It will look like this after substitution:
替换后将如下所示:
a;bc;d;{a,b,cd}
ab;cde;f;{ab,c,defg}
ab;{a,b,cd};cde;f
...
How should I do it in shell command? 我应该如何在shell命令中执行此操作? sed, awk or whatever...
sed,awk或其他...
Perl to the rescue: Perl解救:
perl -pe 's/({.*?})/ $1 =~ s=;=,=gr /ge' input
The problem is your expected output is wrong: 问题是您的预期输出错误:
a;b;cd a;b;cd
| |
V V
a,b,c,d ab,cd
Through perl which uses positive lookahead , 通过使用正向预测的 perl,
$ perl -pe 's/;(?=[^{}]*})/,/g' file
a;bc;d;{a,b,cd}
ab;cde;f;{ab,c,defg}
ab;{a,b,cd};cde;f
sed ':a; s/\(.*\)\({\)\([^;]*\)\(;\)\([^}]*}.*\)/\1\2\3,\5/;t a' file
put a label in the beginning and section off hold patterns and loops around until no more successful substitutions on each line (ta) 在开头放置一个标签,然后放开暂挂模式,然后循环,直到每行(ta)不再成功替换为止
E.g.
a;bc;d;{a;b;cd}morestuff{bsdj;dsfkjl;sdkjl;kd}
ab;cde;f;{ab;c;defg}
ab;{a;b;cd};cde;f
Output:
a;bc;d;{a,b,cd}morestuff{bsdj,dsfkjl,sdkjl,kd}
ab;cde;f;{ab,c,defg}
ab;{a,b,cd};cde;f
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.