convert a fixed width file from text to csv

Ashish picture Ashish · Feb 17, 2015 · Viewed 8k times · Source

I have a large data file in text format and I want to convert it to csv by specifying each column length.

number of columns = 5

column length

[4 2 5 1 1]

sample observations:

aasdfh9013512
ajshdj 2445df

Expected Output

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

Answer

Thor picture Thor · Feb 17, 2015

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,2
ajsh,dj, 2445,d,f