我有一个记录文件没有任何分隔符分隔。下面分享了一个示例:
XXXXXYYYYZZZ
XXXXXYYYYZZZ
XXXXXYYYYZZZ
XXXXXYYYYZZZ
XXXXXYYYYZZZ
我已经为文件提供了DDL,使得字段1位于1-5位置,字段2位于6-9位置,字段3位于10-12位置
如何使用awk命令打印下面的输出?
FIELD1,FIELD2,字段3
XXXXX,YYYY,ZZZ
XXXXX,YYYY,ZZZ
XXXXX,YYYY,ZZZ
XXXXX,YYYY,ZZZ
XXXXX,YYYY,ZZZ
答案 0 :(得分:1)
使用FIELDWIDTHS
的GNU awk:
$ awk '
BEGIN {
FIELDWIDTHS="5 4 3" # here you state the field widths
OFS="," # output field separator
print "field1","field2","field3" } # print header in BEGIN
{
print $1,$2,$3 } # print 3 first fields, you could also:
' file # {$1=$1; print} or even:
field1,field2,field3 # {$1=$1}1
XXXXX,YYYY,ZZZ
XXXXX,YYYY,ZZZ
XXXXX,YYYY,ZZZ
XXXXX,YYYY,ZZZ
XXXXX,YYYY,ZZZ
如果您没有GNU awk,请使用f1=substr($0,1,5);f2=substr($0,6,4)...print f1,f2,f3
。
修改强>
$ awk '
BEGIN {
OFS=","
print "field1","field2","field3" }
{
f1=substr($0,1,5)
f2=substr($0,6,4)
f3=substr($0,10,3)
print f1,f2,f3 }
' file
作为插入;
s的单行后者:
$ awk 'BEGIN {OFS=","; print "field1","field2","field3"}{f1=substr($0,1,5); f2=substr($0,6,4); f3=substr($0,10,3); print f1,f2,f3}' file
前者为单线:
$ awk 'BEGIN{FIELDWIDTHS="5 4 3"; OFS=","; print "field1","field2","field3"}{print $1,$2,$3}' file
答案 1 :(得分:1)
这可能对您有用(GNU sed):
sed -e '1i\field1,field2,field3' -e 's/[^,]/,&/6;s//,&/10' file