简体   繁体   English

使用awk / sed将数字字符串分成3列

[英]Separate string of digits into 3 columns using awk/sed

I have a string of digits in rows as below: 我的行中有一串数字,如下所示:

6390212345678912011012112121003574820069121409100000065471234567810
6390219876543212011012112221203526930428968109100000065478765432196

That I need to split into 6 columns as below: 我需要分成6列,如下所示:

639021234567891,201101211212100,3574820069121409,1000000,654712345678,10
639021987654321,201101211222120,3526930428968109,1000000,654787654321,96

Conditions: 条件:

  • Field 1 = 15 Char 栏位1 = 15个字元
  • Field 2 = 15 Char 栏位2 = 15个字元
  • Field 3 = 15 or 16 Char 栏位3 = 15或16个字元
  • Field 4 = 7 Char 栏位4 = 7个字元
  • Field 5 = 12 Char 栏位5 = 12个字元
  • Field 6 = 2 Char 栏位6 = 2个字元

Final Output: 最终输出:

639021234567891,3574820069121409,654712345678
639021987654321,3526930428968109,654787654321

It's not clear how detect whether field 3 should have 15 or 16 chars. 目前尚不清楚如何检测字段3应该包含15个字符还是16个字符。 But as draft for the first 3 fields you could use something like that: 但作为前3个字段的草稿,您可以使用类似以下内容的代码:

     echo 63902910069758520110121121210035748200670169758510 |
 awk '{ printf("%s,%s,%s",substr($1,1,15),substr($1,16,15),substr($1,30,15)); }'

Or with sed: 或使用sed:

echo $NUM | sed -r 's/^([0-9]{16})([0-9]{15})([0-9]{15,16}) ...$/\1,\2,\3, .../'

This will use 15 or 16 for the length of field 3 based the length of the whole string. 基于整个字符串的长度,这将对字段3的长度使用15或16。

If you're using gawk : 如果您使用的是gawk

gawk -v f3w=16 'BEGIN {OFS=","; FIELDWIDTHS="15 15 " f3w " 7 12 2"} {print $1, $3, $5}'

Do you know ahead of time what the width of Field 3 should be? 您提前知道字段3的宽度是多少吗? Do you need it to be programatically determined? 您是否需要以编程方式确定它? How? 怎么样? Based on the total length of the line? 基于线的总长度? Does it change line-by-line? 它会逐行更改吗?

Edit: 编辑:

If you don't have gawk , then this is a similar approach: 如果您没有gawk ,那么这是一种类似的方法:

awk -v f3w=16 'BEGIN {OFS=","; FIELDWIDTHS="15 15 " f3w " 7 12 2"; n=split(FIELDWIDTHS,fw," ")} { p=1; r=$0; for (i=1;i<=n;i++) { $i=substr(r,p,fw[i]); p += fw[i]}; print $1,$3,$5}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM