【问题标题】:Multiple variables from file inside AWK来自 AWK 内文件的多个变量
【发布时间】:2018-10-11 00:28:12
【问题描述】:

我有一个名为 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

【问题讨论】:

  • 一定要用awk吗?这看起来像是 grep -f users.txt input.txt 的工作。
  • grep -F -f users.txt -A 6 input.txt
  • @Barmar 我需要找到每个模式,一旦找到该模式,就可以打印该模式和接下来的 6 行。据我所知,AWK 是最好的解决方案,除非你能告诉我其他方式。
  • 这不是-A 6 选项到grep 的作用吗?你真的让这件事变得比需要的更难。
  • @Barmar grep: 非法选项 -- F SunOS 5.10 Generic_150400-48 sun4u sparc SUNW,Sun-Fire-V490

标签: bash loops unix awk


【解决方案1】:

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

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-

【讨论】:

  • 我得到语法错误,复制粘贴你的确切脚本:awk: syntax error near line 1 awk: illegal statement near line 1 awk: syntax error near line 2 awk: bailing out near line 2
  • 它在 Mac OS 上对我来说很好用。我无法在 Solaris 上进行测试。
  • 我以前的版本期望模式匹配整行,我删除了正则表达式锚。但这意味着alex 也将匹配alexis
【解决方案2】:

你也可以使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多