Merge lines in Flat file based on first 5 characters

Hi

I have the fixed width flat file having the following data

12345aaaaaaaaaabbbbbbbbbb
12365sssssssssscccccccccc
12365sssss
12367ddddddddddvvvvvvvvvv
12367 vvvvv

Here the first column is length 5 second is length 10 third is length 10

if the second or third column exceeds length it is repeated in next line with the first column repeated

Now I need the file to be modified in such a way that there is only one row for the data like

12345aaaaaaaaaa bbbbbbbbbb
12365sssssssssssssss cccccccccc
12367dddddddddd vvvvvvvvvvvvvvv

changing the lenght of the second and third column to 20 instead of 10.
I am trying to write this in perl or shell.
Kindly help me..

If awk is acceptable (use nawk or /usr/xpg4/bin/awk on Solaris):

awk 'END {
  print fmt(k, _[k])
  }
NR > 1 && substr($0, 1, 5) != k {
  print fmt(k, _[k])
  }
{
  k = substr($0, 1, 5)
  v = substr($0, 6)
  _[k] = _[k] ? _[k] v : v
  }
func fmt(k, v) { 
  return k  sprintf("%-20s%-20s",\
  substr(v, 1, 10), substr(v, 11))
  }' infile

Thank You for the code.

Is there any way that i could do this in perl.

Something like this:

perl -ne'
  /(.{5})(.*)/ and $h{$1} .= $2 ;
  print map { 
    $_, sprintf( "%-20s%-20s", $h{$_} =~ /(.{10})(.*)/ ), "\n" 
    } sort { $a <=> $b } keys %h if eof
    ' infile