colh = {"IDS007" => false } table = [] disci = nil key = nil for line in ARGF case line when /^IDS007:/ disci = line.split(/\s+/)[2] when /^PDS001:/ h = {'IDS007'=>disci} table.push h when /^(PDS(?:010|011)):/ key = $1 v = line.split(/\s+/)[2] table.last[key] = v colh[key] = true when /^([A-Z]+\d+):/ key = $1 when /^ \(/ if key == 'PDS011' then table.last[key + 'v'] = line.chomp.gsub(/^ \(=?\s*|\)$/, '') colh[key + 'v'] = true end end end cols = colh.keys.sort_by{|k| k.sub(/^PDS/, '4.').sub(/^IDS/, '1.') } puts cols.join("\t") for row in table puts cols.map{|c| row[c]}.join("\t") end