Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to convert Fixed Width File to 'Comma' delimited in unix

Tags:

unix

Need to convert Fixed Width File to 'Comma' delimited in unix.

k12582927001611USNA
k12582990001497INAS
k12583053001161LNEU

Required output:

k,1258292700,1611,US,NA
k,1258299000,1497,IN,AS
k,1258305300,1161,LN,EU
like image 207
code_baby Avatar asked Nov 30 '22 00:11

code_baby


1 Answers

Like this:

awk -v FIELDWIDTHS="1 10 4 2 2" -v OFS=, '{print $1,$2,$3,$4,$5}' file

OFS is the Output Field Separator and I set it to a comma. The FIELDWIDTHS variable does all the magic for you.

Or you can do it in Perl like this:

perl -ne 'm/(.)(.{10})(....)(..)(..)/; printf "%s,%s,%s,%s,%s\n",$1,$2,$3,$4,$5' file

Or, in sed like this:

sed -E 's/(.)(.{10})(....)(..)(..)/\1,\2,\3,\4,\5/' file
like image 54
Mark Setchell Avatar answered Dec 06 '22 09:12

Mark Setchell