How to run grep inside awk?

后端 未结 6 2138
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-15 11:22

Suppose I have a file input.txt with few columns and few rows, the first column is the key, and a directory dir with files which contain some of these

6条回答
  •  执笔经年
    2021-02-15 12:09

    You don't need grep with awk, and you don't need cat to open files:

    awk 'NR==FNR{keys[$1]; next} {for (key in keys) if ($0 ~ key) {print FILENAME, $0; next} }' input.txt dir/*
    

    Nor do you need xargs, or shell loops or anything else - just one simple awk command does it all.

    If input.txt is not a file, then tweak the above to:

    real_input_generating_command |
    awk 'NR==FNR{keys[$1]; next} {for (key in keys) if ($0 ~ key) {print FILENAME, $0; next} }' - dir/*
    

    All it's doing is creating an array of keys from the first file (or input stream) and then looking for each key from that array in every file in the dir directory.

提交回复
热议问题