Wednesday, 18 November 2015

How to Convert Fixed Width File to Delimited Using AWK

Input File: F_Data_File.txt

1001A110USAY
1002A210GBRY
1003A320NLDY
1004A430CANY
1005A540INDY

Desired Output:

1001,A1,10,USA,Y
1002,A2,10,GBR,Y
1003,A3,20,NLD,Y
1004,A4,30,CAN,Y
1005,A5,40,IND,Y

Solution:

$ awk -v FIELDWIDTHS='4 2 2 3 1' -v OFS=',' '{ $1=$1 ""; print }' F_Data_File.txt

$ awk '{
    V_Field1=substr($0,1,4)
    V_Field2=substr($0,5,2)
    V_Field3=substr($0,7,2)
    V_Field4=substr($0,9,3)
    V_Field5=substr($0,12)
printf ("%s,%s,%s,%s,%s\n", V_Field1, V_Field2, V_Field3, V_Field4, V_Field5)}' F_Data_File.txt

$ awk '{
    V_Field1=substr($0,1,4)
    V_Field2=substr($0,5,2)
    V_Field3=substr($0,7,2)
    V_Field4=substr($0,9,3)
    V_Field5=substr($0,12)
print(V_Field1","V_Field2","V_Field3","V_Field4","V_Field5)}' F_Data_File.txt

Explanation:

Substring function syntax : substr(str,start_position,length_of_string)
First Field = String
Second Field = Position to Start
Third Field = Length from position to start

1 comment:

Related Posts Plugin for WordPress, Blogger...