Surya
Surya

Reputation: 4972

awk search for a field in another file

i need to search for fields from one file in second file. Wondering if awk is right solution

file 1

one
two

file 2

something one
balh   one
blah two
blah two

required output

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

i was hoping i could use awk with in awk , searching for each line within the second and constructing the output.

Upvotes: 4

Views: 5518

Answers (2)

Hai Vu
Hai Vu

Reputation: 40733

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

grep -f file1 file2

The above command search file2 for every tokens in file1.

Upvotes: 3

glenn jackman
glenn jackman

Reputation: 246847

One invokation of awk is sufficient

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}

Upvotes: 3

Related Questions