首页 > 解决方案 > 来自 AWK 内文件的多个变量

问题描述

我有一个名为的文件users.txt,其中包含以下格式的用户列表:

bob
john
alex
tom

我需要运行这个 AWK 语句并将这些名称中的每一个用作模式并输出到文件

awk '/PATTERN/{x=NR+6}(NR<=x){print}' input.txt >> output.txt

如何让 AWK 循环遍历每个名​​称并将它们用作搜索模式?

示例输入文件:

bob@servername
10/09/2018 19:11:19
50152 command issued.

  weid: A1Pz64385236
  job_name: xxx-xxx-xxx-xxx-xxx-xxx
  command: fff-fff-fff-fff-
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
alex@servername
10/09/2018 16:33:55
50152 command issued.

  weid: A1Pz64385236
  job_name: xxx-xxx-xxx-xxx-xxx-xxx
  command: fff-fff-fff-fff-
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
doug@servername
10/09/2018 13:22:66
50152 command issued.

  weid: A1Pz64385236
  job_name: xxx-xxx-xxx-xxx-xxx-xxx
  command: fff-fff-fff-fff-
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::`

输出应该是这样的,只有 users.txt 文件中的用户(输入文件中有很多我不想看到的用户)

bob@servername
10/09/2018 19:11:19
50152 command issued.

  weid: A1Pz64385236
  job_name: xxx-xxx-xxx-xxx-xxx-xxx
  command: fff-fff-fff-fff

标签: bashloopsunixawk

解决方案


在读取第一个文件时,将每一行附加到一个模式字符串,用 . 分隔它们|。然后在处理第二个文件时根据模式测试该行。

awk 'NR==FNR { pattern = pattern (pattern ? "|" : "") $0; next }
     $0 ~ pattern { x = FNR + 6 }
     FNR <= x' users.txt input.txt

我使用您的示例文件在 Mac OS High Sierra 和 Debian Linux 上对此进行了测试,结果是:

bob@servername
10/09/2018 19:11:19
50152 command issued.

  weid: A1Pz64385236
  job_name: xxx-xxx-xxx-xxx-xxx-xxx
  command: fff-fff-fff-fff-
alex@servername
10/09/2018 16:33:55
50152 command issued.

  weid: A1Pz64385236
  job_name: xxx-xxx-xxx-xxx-xxx-xxx
  command: fff-fff-fff-fff-

推荐阅读