first I'd try the obvious and try to read smaller_file completely into mem - 20MB is not too much for current systems: fileNames = File.open("smaller_file.txt", "r") do |f| h = {} f.each do |line| line.chomp! line.strip! h[line]=true end h end File.open("expanded_file.txt","w") do |expanded| File.open("big_file.txt", "r") do |f| f.each do |line| line.chomp! line.strip! expanded.puts line if fileNames.has_key? File.basename(line) end end end Cheers robert