Skip to main content

Merging multiple files columnwise

Here's a little parser script, to merge multiple files. Each file has a header and a time course. I need all time courses in a single file, next to each other.

basedir = "./MassSpectrum/"

allData = [] # ms data from all files

filelist = Dir.new(basedir).entries
filelist.each {|f|
  if f !~ /\.txt/ # f is not a data file
    next
  end

  data = [] # ms data from this files
  massToCharge = 50
  readData = false # set to true once we are reading in ms data
  File.open( basedir+f).each { |line|
    case line
    when /^SPECTRUM/
      next
    when /raw/
      data.push line.chop.rstrip
      puts ":#{line.chop.rstrip}:"
      next
    when /^Mass/
      puts "starting"
      readData= true
      next
    end

    if readData # we are reading ms data, should go from 50 to 650
      arr = line.split
      while arr.first.to_i != massToCharge # a mass to charge ratio was skipped
        data.push 0
        massToCharge = massToCharge + 1
      end
      data.push arr.last
      massToCharge = massToCharge + 1
    end
  }
  allData.push data
}
open("results.xls","w") { |out|
  for i in 0..allData.first.size do
    allData.each{ |l|
      out << l[i]
      out << "\t"
    }
    out << "\n"
  end
}

Comments