【问题标题】:awk - search for multiple strings in file and store specific word from this line to print all of them on one line at the endawk - 在文件中搜索多个字符串并存储这一行中的特定单词以在最后一行打印所有字符串
【发布时间】:2021-06-30 13:55:45
【问题描述】:

我是这个论坛的新手,刚开始使用 awk,我喜欢做以下事情。

输入文件(input.log):

first word of file
second line in file
third and last line

awk 脚本 (test.awk) 到目前为止,我找到了字符串并将它们存储在一行的末尾打印:

/first/ ( aaa = $2 )
/in/ ( bbb = $1 )
/last/ ( ccc = $3 )
{ print aaa " , " bbb " , " ccc }

awk -f test.awk input.log

实际输出:

first word of file
first word of file
first word of file
word , first , of
second line in file
second line in file
second line in file
line , second , in
third and last line
third and last line
third and last line
and , third , last

预期(想要的)输出:

word , second , last

任何帮助和建议将不胜感激。

兄弟。伯特

【问题讨论】:

  • 您的脚本似乎使用圆括号() 需要大括号。你说你想在最后打印结果,但是你没有END 块。

标签: awk


【解决方案1】:

我想你的意思是用{} 而不是()

/ first / { aaa = $2 }
/ in / { bbb = $1 }
/ last / { ccc = $3 }
END { print aaa " , " bbb " , " ccc }

如果您省略 regex /in/ 周围的空格,您的脚本将匹配包含单词 in 的行以及其他行中出现的单词 line

最后一条语句必须以END 开头,并且在处理整个文件时只会执行一次。

【讨论】:

  • Jonathan Leffler 刚才说的和我在他上面的评论中说的一样,但他没有看到 regex 周围缺少空格的问题。
  • 更准确地说,我没有对此发表评论:D。我对输出中重复行的数量感到困惑。第一行有 3 次重复,但我认为四种模式(/first/( aaa = $2 )( bbb = $1 )( ccc = $3 ))中的每一种都会触发隐式的print $0 操作。 […时间过去了;启蒙罢工...] 除了现有的{ print … }( ccc = $3 ) 相关联。我认为这并不能完全解释它,除非问题中脚本中的行距与实际使用的行距不同。
  • 非常感谢您的帮助和解释原因!!
  • @JonathanLeffler 脚本的每一行都有一个真实的条件,因为他们说,例如/first/ ( aaa = $2 ) 这是$0 ~ /first/ 结果的字符串连接,它是 0 或 1 的结果aaa=$2 是 $2 中的任何字符串,因此结果是一个像 1word0line 这样的字符串,无论是什么始终是一个非空字符串,然后将其视为真实条件以导致默认打印当前行。对变量的赋值总是发生,因此脚本完全按照发布的方式生成问题中显示的输出。
  • @EdMorton — 谢谢。我没有想到您可以在pattern action 行的模式部分中的术语之间进行强连接。这不是我曾经需要的东西,我不确定在很多情况下它是否有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 1970-01-01
  • 2022-11-13
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
相关资源
最近更新 更多