austinmoody
8/18/2010 - 8:10 PM

Split HL7 files (by MSH segment) into files of 500 message each.

Split HL7 files (by MSH segment) into files of 500 message each.

# Split HL7 files (by MSH segment) into files of 500 message each
def main()

	in_files = Dir.glob(File.join("C:","Users","Austin","Documents","CareSpark","Provider Sources","WHS","ORUReplay","*.hl7"))
	
	current_file = Array.new
	msh_count=0
	file_count=0
	
	in_files.each do |file|
	
		

		# open the file
		input_file = File.open(file)
		input_file.readlines("\x0D").each do |seg|

			if (seg[0,3] == 'MSH')
				if (current_file.length != 0 and msh_count == 500)
					output_filename = "whs" + Time.new.strftime("%Y%m%d%H%M%S") + "_#{file_count}.hl7"
					output_file = File.open("SplitFiles/" + output_filename,"w")

					output_file.write(current_file)
					output_file.close

					current_file = Array.new
					msh_count = 0

					file_count += 1

				end

				msh_count += 1


			else
				#seg = seg + "\x0d"
			end

			current_file.push(seg)		
		end


		input_file.close

	end # loop over files
	
	# catch anything left over
	if (current_file.length != 0)
		output_filename = "whs" + Time.new.strftime("%Y%m%d%H%M%S") + "_#{file_count}.hl7"
		output_file = File.open("SplitFiles/" + output_filename,"w")

		output_file.write(current_file)

		output_file.close		

	end
	
end # def main

main()