这是我的文本文件:
0019121002313002316003135
0057936000814000814003023
0081638001519001523001176
0090531001841001842002633
0111210001515001518000912
0115400001807001828001593
我希望处理后的输出为:
0019121,002313,002316,003135
0057936,000814,000814,003023
0081638,001519,001523,001176
0090531,001841,001842,002633
0111210,001515,001518,000912
0115400,001807,001828,001593
我该怎么做呢?
答案1
$ sed -E 's/(.{7})(.{6})(.{6})(.{6})/\1,\2,\3,\4/' file
0019121,002313,002316,003135
0057936,000814,000814,003023
0081638,001519,001523,001176
0090531,001841,001842,002633
0111210,001515,001518,000912
0115400,001807,001828,001593
也就是说,匹配组成新字段的每一行的位并在它们之间插入逗号。字段的匹配是使用.{7}
或.{6}
取决于所需的字段长度来完成的。
答案2
使用 GNU awk ( gawk
),您可以设置显式字段宽度:
$ gawk '{$1=$1} 1' FIELDWIDTHS='7 6 6 6' OFS=, file
0019121,002313,002316,003135
0057936,000814,000814,003023
0081638,001519,001523,001176
0090531,001841,001842,002633
0111210,001515,001518,000912
0115400,001807,001828,001593
答案3
假设第一个逗号在7个字符之后,接下来的逗号是6的倍数,这不是一个错误,我建议
sed 's/\(.......\)\(......\)\(......\)/\1,\2,\3,/'