One awk call is enough
awk ' FNR == NR { # reading file1 values[$1] = "" next } { # reading file2 for (elem in values) if ($0 ~ elem) if (values[elem] == "") values[elem] = "\"" $0 "\"" else values[elem] = values[elem] ", \"" $0 "\"" } END { for (elem in values) print elem " [" values[elem] "]" } ' file1 file2
Probably easier in something like Ruby
keys = File.readlines("file1").collect {|line| line.chomp} values = Hash.new {|h,k| h[k] = []} File.foreach("file2") do |line| line.chomp! keys.each do |key| if line.include?(key) values[key] << line end end end values.each {|key,value| puts key + " " + value.inspect}
source share