Re: to convert a csv file to fixed width File

10 views
Skip to first unread message
Message has been deleted

Keith Bradnam

unread,
Sep 22, 2014, 5:35:01 PM9/22/14
to unix-and-perl-...@googlegroups.com
In Perl you could read the file one line at a time, split each line on commas (using the split function), and then print the output using printf (or sprintf):


See the section on 'flags'.

Keith


On Friday, September 12, 2014 9:49:03 AM UTC-7, jabir m wrote:
Hello -
Thanks in advance for your reply.. I am trying to convert delimited file to fixed width with different column width. 
I am able to convert when the column width same for all column or the number of field in the file is constant.

My scenario is i have file which is generating variable number of column in different time and i have to convert into fixed width file based on the field width given.

Example 1
I have got a file with 4 column with csv and  given Field length (10 6 7 8 )

i/p
201401,12,15,767
201401,123,154,45
201401,125,152,6789
201401,121,8815,45
201401,1266,185,1

o/p

201401    12    15     767
201401    123   154    45
201401    125   152    6789
201401    121   8815   45
201401    1266  185    1


But sometimes i may get  the file with different set of columns (eg: 6 columns and Field length (8 8 10 10 20 5 )


So in this case what will be the best scenario i can write a code to handle these kind of situation. (variable number of fields and different column width)

I tried following method, but it gives me some extra spaces than expected.

Inside a loop, passed the field length and field numbers
nawk -F~  '{ printf "%'$filed_len's   \n", $'$field_no'  }' ${src_dat} >${src_dat}"t."$field_no
End of loop
paste $BATCH_IN/${src_dat}"t."* > $BATCH_IN/${src_dat} 


Thanks 
Jabir
Reply all
Reply to author
Forward
0 new messages