AWK中文件中的多个变量

时间:2018-10-11 00:28:12

标签: bash loops unix 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

2 个答案:

答案 0 :(得分:0)

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

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-

答案 1 :(得分:0)

您可能也可以使用grep:

grep input -wf users -A 6

这会将用户文件中的名称与输入文件进行匹配,并在匹配后打印6行。使用w标志,grep将仅匹配完整的单词,您可以根据需要将其省略。

如果您的grep不支持-A,则可能会起作用:

grep input -wf users -n | cut -d: -f1 | xargs -n 1 -I {} sed -n "{},/^::*$/ p" input

或者这个:

grep input -wf users | xargs -n 1 -I {} sed -n "/{}/,/^::*$/ p" input