【问题标题】:How to find lines with multiple occurrences of a(ny) word in a file?如何在文件中查找多次出现 a(ny) 单词的行?
【发布时间】:2015-01-23 05:12:06
【问题描述】:

我想查找多次出现 a(ny) 单词的行。例如,如果输入文本是

John is a teacher, who is not highly paid.
abc abcde
James lives in Detroit.
abc abc abcde
Paul has 2 dogs and 2 cats.

输出应该是

John is a teacher, who is not highly paid.
abc abc abcde
Paul has 2 dogs and 2 cats.

第一行重复is,第二行重复abc,最后一行重复2

【问题讨论】:

  • 第二行重复了abc。你的意思是重复的单词吗?
  • 是的,但是任何单词,而不是特定单词。
  • 请修正问题。它说任何字符串,而不是任何单词。因此,我发布了错误的答案。
  • 我为你编辑了它。是的,它是空白。字符串是任何字符序列,例如bc 里面的abcde 是一个字符串。单词是由空格或标号包围的字母和数字序列。
  • 我在一定程度上不同意。从这个意义上说,每个字母/字符都可以称为字符串。 “约翰住在底特律”也应该出现,因为 i,n,e,t,o,i 都是重复的!

标签: regex grep field multiple-columns custom-fields


【解决方案1】:
^(?=.*\b(\w+)\b.*\b\1\b).*$

试试这个。查看演示。

https://www.regex101.com/r/rG7gX4/6

将此与grep -P 一起使用

【讨论】:

  • 是的,它有效。谢谢。我正在尝试理解该命令,以及它是否适用于 *x! 的所有变体!
  • 你得到了我的 +1。 “?=”是什么意思?
  • @qqibrow 表示前瞻。它是一个 0 宽度的断言,只检查前面的条件
  • 'grep - P' 不适用于所有 shell。在某些 shell 中,我确实得到了“grep:不支持 -P 选项”。
【解决方案2】:

这是awk的简单方法

awk '{f=0;delete a;for (i=1;i<=NF;i++) if (a[$i]++) f=1} f' file
John is a teacher, who is not highly paid.
abc abc abcde
Paul has 2 dogs and 2 cats.

它循环遍历每个单词并将它们计数到数组a
如果发现任何单词不止一次,设置标志f
如果标志f 为真,则执行默认操作,打印行。


看看有多少:

awk '{f=0;delete a;for (i=1;i<=NF;i++) if (a[$i]++) f=1} f {for (i in a) if (a[i]>1) printf "%sx\"%s\"-",a[i],i;print $0}' file
2x"is"-John is a teacher, who is not highly paid.
2x"abc"-abc abc abcde
2x"2"-Paul has 2 dogs and 2 cats.

一些改进:忽略大小写。删除.,

awk '{f=0;delete a;for (i=1;i<=NF;i++) {w=tolower($i);sub(/[.,]/,"",w);if (a[w]++) f=1}} f' file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    相关资源
    最近更新 更多