Merge a group of lines into single line

Hi Everybody,

Below are the contents of the a text file ..,

SN = 8
MSI = 405027002277133
IKVALUE = DE6AA6A11D42B69DF6398D44B17BC6F2
K4SNO = 2
CARDTYPE = SIM
ALG = COMP128_3
SN = 8
MSI = 405027002546734
IKVALUE = 1D9F8BAA73973D8FBF8CBFB01436D822
K4SNO = 2
CARDTYPE = SIM
ALG = COMP128_3

I am looking to merge a group of lines into single line as noted below ..,

SN = 8,MSI = 405027002277133,IKVALUE = DE6AA6A11D42B69DF6398D44B17BC6F2,K4SNO = 2,CARDTYPE = SIM,ALG = COMP128_3
SN = 8,MSI = 405027002546734,IKVALUE = 1D9F8BAA73973D8FBF8CBFB01436D822,K4SNO = 2,CARDTYPE = SIM,ALG = COMP128_3

Can anyone help me in the same.

$ ruby -00 -ne '$_.split(/^SN/).each{|x|x.strip!;puts "SN#{x.gsub("\n",",")}" if x!=""}' file
SN= 8,MSI = 405027002277133,IKVALUE = DE6AA6A11D42B69DF6398D44B17BC6F2,K4SNO = 2,CARDTYPE = SIM,ALG = COMP128_3
SN= 8,MSI = 405027002546734,IKVALUE = 1D9F8BAA73973D8FBF8CBFB01436D822,K4SNO = 2,CARDTYPE = SIM,ALG = COMP128_3

awk 'END { print r }
r && /^SN/ {
  print r; r = x
  }  
{ 
  r = r ? r OFS $0 : $0 
  }' OFS=, infile  

One more with tr and sed:

tr -s '\n' ',' < infile| sed -e 's/,SN/\nSN/g' -e 's/,$/\n/'

With Perl:

perl -lne'
  do {
    print join ",", @l;
    @l = ()
    } if @l and /^SN/;
    push @l, $_;
    print join ",", @l 
      if eof
   ' infile

Without invoking external command

#!/bin/bash

while read line
do
   if [[ $line =~ ^SN(.*) ]]
   then
      [[ -n $out ]] && echo $out
      out="$line"
   else
      out="$out, $line"
   fi
done  < infile
echo $out

could you explain this to me further?

while read line
do
   if [[ $line =~ ^SN(.*) ]] <-- line that starts with SN and whatever
   then
      [[ -n $out ]] && echo $out    <--when was $out defined or is it reserved?
      out="$line"
   else
      out="$out, $line"
   fi
done  < infile
echo $out

$out is not a reserved variable; it is a regular shell variable. It is "defined" wherever you see "out=" in the shell script.

Seems crude but work done !!

bash-3.00$ nawk '{if ($3 == "COMP128_3") ORS="\n" ; else ORS="," } 1 '