【问题标题】:awk giving different behavior on different systemsawk 在不同的系统上给出不同的行为
【发布时间】:2014-05-30 17:40:17
【问题描述】:

我正在使用 awk 对包含特定关键字的段落进行 grep,直到记录分隔符在我的情况下是空格。

awk -vRS= /\<keyword2\>/ file.txt

file.txt 包含这个

this is the first keyword1 occurance
and line in the first paragraph

this is the second keyword2 occurance
and line in the second paragraph

现在awk 命令的输出应该是

this is the second keyword2 occurance
and line in the second paragraph

但它只适用于我的一个系统。对其他人不起作用。请帮忙

发现错误
在 Ubuntu 14.04 上安装了 nawk 并且不起作用。
gawk 一起工作正常

【问题讨论】:

  • 什么意思是不能在其他系统中工作?哪个系统是你的,哪个是其他的?
  • 在一些 ubuntu 系统上
  • 我猜这是由于我想要的一些精确的单词匹配行为
  • 好像有帖子说加单引号没用。

标签: bash awk


【解决方案1】:

你和你的awk非常亲密

cat file
More data
this is the first keyword1 occurance
and line in the first paragraph

Another data
this is the second keyword2 occurance
and line in the second paragraph

awk -v RS= '/\<keyword2\>/' file
Another data
this is the second keyword2 occurance
and line in the second paragraph

你也可以尝试跳到单词边界:

awk -v RS= '/keyword2/' file

perl 版本:

perl -ne 'BEGIN { $/="\n\n" }; print if $_ =~ /keyword2/;' file

sed版本

sed -e '/./{H;$!d;}' -e 'x;/\<keyword2\>/!d;' file

Another data
this is the second keyword2 occurance
and line in the second paragraph

sed -e '/./{H;$!d;}' -e 'x;/keyword2/!d;' file

【讨论】:

  • @perreal 它确实包含单引号 '
  • 如果您真的很无聊,请查看我的答案的先前版本。 OP 说单引号无济于事。
  • @perreal 这不应该被删除,因为它对新用户来说也很重要获取此信息。它可能有助于删除单词边界。我更新原帖。您也可以尝试修改sed 以获得完整的段落。
  • @dreamer 什么不起作用?我在 4 个不同的系统上进行了尝试,第一篇文章中发布的数据一切正常。你有其他数据吗?你的系统是什么?
  • 我安装了标准的 Ubuntu 14.04 LTS。
【解决方案2】:

你可以试试sed:

sed -n '/\<keyword2\>/,/^$/p' file.txt

【讨论】:

  • 不,这样不行。什么都没找到
  • 它可能与边界这个词有关。如果我删除单词边界检查,那么它可以工作,但我想要确切的单词匹配!
  • @dreamer,awk 对我有用,所以无能为力,但您可以尝试上面的 sed 命令
  • @dreamer 如果段落中有更多行并且keyword2 不在第一行,这将失败。您在段落中要求一个关键字,而不是告诉它在哪里。然后它将错过段落中关键字中的上述行。 (参见我的帖子中的示例)。
  • @Jotne 好吧,我没有检查上面的sed code 以查看它是否适用于关键字位于段落中间的段落。我的要求非常具体,关键字对我来说永远是段落的开头。 :)
【解决方案3】:

听起来您正试图在不兼容的 awk 实现上使用 GNU awk extensions

不幸的是,没有 POSIX 标准的单词边界标记。根据文本的具体内容,您可能可以使用:

awk -vRS= '/[[:space:]]keyword2[[:space:]]/' file.txt

这将匹配keyword2 两边有空格。这应该适用于 awk 的任何实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多