【问题标题】:awk search for a field in another fileawk 在另一个文件中搜索字段
【发布时间】:2019-02-26 22:31:25
【问题描述】:

我需要从第二个文件中的一个文件中搜索字段。想知道 awk 是否是正确的解决方案

文件 1

one
two

文件 2

something one
balh   one
blah two
blah two

需要的输出

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

我希望我可以在 awk 中使用 awk,在第二行中搜索每一行并构建输出。

【问题讨论】:

  • 文件有多大?在 awk 中编写代码可能是可能的,但如果两个文件中都有 100000 行,则不太可能扩展。

标签: awk


【解决方案1】:

一次调用 awk 就足够了

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

在 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】:

    如果您愿意接受稍微不同的输出以换取更简单的解决方案,那么 grep 就是您的工具:

    grep -f file1 file2
    

    上述命令在 file2 中搜索 file1 中的每个标记。

    【讨论】:

      猜你喜欢
      • 2018-05-31
      • 2016-11-06
      • 2016-02-08
      • 1970-01-01
      • 2016-04-03
      • 2017-03-05
      • 2019-06-23
      • 2011-03-27
      • 1970-01-01
      相关资源
      最近更新 更多