Awk field search in another file

I need to search fields from one file in a second file. Wondering if awk is the right solution

file 1

one two 

file 2

 something one balh one blah two blah two 

required conclusion

 one ["something one", "blah one"] two [ "blah two" , "blah two"] 

I was hoping I could use awk with awk, searching every line per second and constructing the output.

+4
source share
2 answers

If you are ready to accept a slightly different result in exchange for a simpler solution, then grep is your tool:

 grep -f file1 file2 

The above search batch file2 for each token in file1.

+3
source

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} 
+2
source