0

在正则表达式中,如何匹配某个水平位置的字符?我想n用逗号后跟三个空格替换逗号位置,即

s/,/, /        # replace ',' at position n=4 with ', '

但是这些正则表达式仍然错过了水平位置约束。

和...一起

s/,/,  /       # replace ',' at position n=3 with ',  '
s/,/,   /      # replace ',' at position n=2 with ',   '

我想用它来重新格式化数据列,从

1,10000,0.187929453,10000
162,28000,0.045417083,28000
22,100000,0.020914811,100000
64,1000,0.234950091,10000
65,46000,0.037523632,46000
66,118000,0.015378538,118000

1,   10000,  0.187929453, 10000
162, 28000,  0.045417083, 28000
22,  100000, 0.020914811, 100000
64,  1000,   0.234950091, 10000
65,  46000,  0.037523632, 46000
66,  118000, 0.015378538, 118000
4

2 回答 2

3

这里不需要使用正则表达式,这种类型的问题可以使用 awk 轻松解决。考虑以下代码:

awk -F"," 'NF==4{printf("%-5s%-8s%-12s %s\n", $1",", $2",", $3",", $4)}' in.file

现场演示:http: //ideone.com/bXJXX5

于 2013-03-13T09:13:58.940 回答
2

尝试类似:

s/^(.{3}),/$1,   /

语法取决于您的语言。以上适用于 Perl。在某些语言中,它\1不是$1.

大多数语言都有更简单的方法来做你想做的事。Perl 和 C 必须printf格式化输出:

#another Perl example:
printf '%4s %7s %s %s', map({ $_ . ',' }, split(',',$line));
于 2013-03-13T08:47:17.160 回答