Ashish Ashish - 1 year ago 52
Linux Question

convert a fixed width file from text to csv

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:

ajshdj 2445df

Expected Output

ajsh,dj, 2445,d,f

Answer Source

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/' file
ajsh,dj, 2445,d,f