如何为固定长度文件中的每个列重复键值

时间:2016-04-15 11:22:15

标签: unix text awk sed flat-file

我必须在一行中每14个字符后重复键值

我的文件如下:

KEYVALUE1 201604141111I201604141111C201604141111D201604141111E201604141111F  
KEYVALUE1 201604141111G  
KEYVALUE2 201604141111I201604141111C201604141111D201604141111E201604141111F  
KEYVALUE2 201604141111G201604141111F  
KEYVALUE3 201604141111I  
KEYVALUE4 201604141111G201604141111I  

我的输出应该是这样的,

KEYVALUE1 201604141111I  
KEYVALUE1 201604141111C  
KEYVALUE1 201604141111D  
KEYVALUE1 201604141111F  
KEYVALUE1 201604141111G  
KEYVALUE2 201604141111I  
KEYVALUE2 201604141111C  
KEYVALUE2 201604141111D  
KEYVALUE2 201604141111F  
KEYVALUE2 201604141111G  
KEYVALUE2 201604141111F  
KEYVALUE3 201604141111I  
KEYVALUE4 201604141111G  
KEYVALUE4 201604141111I  

请帮忙。

4 个答案:

答案 0 :(得分:1)

sed用于单个行上的简单替换,即全部。对于其他任何事情,您应该使用awk来实现简单性,清晰度,稳健性,可移植性,效率以及软件的大多数其他理想品质:

$ awk '{ while ($2!="") { print $1, substr($2,1,13); $2=substr($2,14) } }' file
KEYVALUE1 201604141111I
KEYVALUE1 201604141111C
KEYVALUE1 201604141111D
KEYVALUE1 201604141111E
KEYVALUE1 201604141111F
KEYVALUE1 201604141111G
KEYVALUE2 201604141111I
KEYVALUE2 201604141111C
KEYVALUE2 201604141111D
KEYVALUE2 201604141111E
KEYVALUE2 201604141111F
KEYVALUE2 201604141111G
KEYVALUE2 201604141111F
KEYVALUE3 201604141111I
KEYVALUE4 201604141111G
KEYVALUE4 201604141111I

答案 1 :(得分:1)

如果你对perl开放:

perl -lane 'print "$F[0] $_" for $F[1] =~/.{13}/g' file

答案 2 :(得分:0)

您可以试试sed

sed -n '/^\([^ ]* \)\(.\{13\}\)/{s/^\([^ ]* \)\(.\{13\}\)/&\n\1/g;P;D;}' file

答案 3 :(得分:0)

或者这个:

sed '{
  :j
  /^[^ ]* .\{13\}.\{13\}/ {
    h
    s/^\([^ ]*\) \(.\{13\}\)\(.*\)$/\1 \2/
    p
    x
    s/^\([^ ]*\) \(.\{13\}\)\(.*\)$/\1 \3/
    h
    b j
  }
}' file