convert a fixed width file from text to csv convert a fixed width file from text to csv linux linux

convert a fixed width file from text to csv


GNU awk (gawk) supports this directly with FIELDWIDTHS, e.g.:

gawk '$1=$1' FIELDWIDTHS='4 2 5 1 1' OFS=, infile

Output:

aasd,fh,90135,1,2ajsh,dj, 2445,d,f


I would use sed and catch the groups with the given length:

$ sed -r 's/^(.{4})(.{2})(.{5})(.{1})(.{1})$/\1,\2,\3,\4,\5/' fileaasd,fh,90135,1,2ajsh,dj, 2445,d,f


Here's a solution that works with regular awk (does not require gawk).

awk -v OFS=',' '{print substr($0,1,4), substr($0,5,2), substr($0,7,5), substr($0,12,1), substr($0,13,1)}'

It uses awk's substr function to define each field's start position and length. OFS defines what the output field separator is (in this case, a comma).

(Side note: This only works if the source data does not have any commas. If the data has commas, then you have to escape them to be proper CSV, which is beyond the scope of this question.)

Demo:

echo 'aasdfh9013512ajshdj 2445df' | awk -v OFS=',' '{print substr($0,1,4), substr($0,5,2), substr($0,7,5), substr($0,12,1), substr($0,13,1)}'

Output:

aasd,fh,90135,1,2ajsh,dj, 2445,d,f