【问题标题】:Grep with regular expressions使用正则表达式进行 Grep
【发布时间】:2012-08-14 13:19:33
【问题描述】:

考虑这个文本文件:

TEST FILE : test                         #No match
                                         #No match
Run grep "1133*" on this file            #Match
                                         #No match
This line contains the number 113.       #Match
This line contains the number 13.        #No match
This line contains the number 133.       #No match
This line contains the number 1133.      #Match
This line contains the number 113312.    #Match
This line contains the number 1112.      #No match
This line contains the number 113312312. #Match
This line contains no numbers at all.    #No match

grep 命令如何评估1133* 正则表达式?

echo "Consider this text file:

TEST FILE : test                         #No match
                                         #No match
Run grep \"1133*\" on this file          #Match
                                         #No match
This line contains the number 113.       #Match
This line contains the number 13.        #No match
This line contains the number 133.       #No match
This line contains the number 1133.      #Match
This line contains the number 113312.    #Match
This line contains the number 1112.      #No match
This line contains the number 113312312. #Match
This line contains no numbers at all.    #No match" | grep "1133*"

输出:

Run grep "1133*" on this file            #Match
This line contains the number 113.       #Match
This line contains the number 1133.      #Match
This line contains the number 113312.    #Match
This line contains the number 113312312. #Match

为什么包含113 的行是肯定的?

正则表达式1133* 是否意味着除了 找出所有包含单词1133+anything else的行?

此示例可在 tldp regexp 文档页面上找到。

【问题讨论】:

  • 1133* 匹配 113 或 1133 或 11333 等,或“出现在 * 之前的任何元素的零次或多次出现”。
  • 您将从学习正则表达式的基础知识中获得巨大的好处(例如here)。
  • Lucian,你能分享你的 grep 命令吗?
  • @AlikElzin-kilaka 我很难记住 8 年前发生了什么,但为了完整起见,我更新了我的问题以包括源代码以及正则表达式本身。

标签: regex linux bash grep


【解决方案1】:

您正在考虑使用 shell 通配符,* 可以匹配任何内容。在 regular expressions 中,*quantifier,表示紧接在其前面的任何内容的“零个或多个”,在本例中为 3

所以你的表达意味着113后跟零个或多个3s。

【讨论】:

    【解决方案2】:

    试试 grep "1133$" 或者 grep "^1133$"

    其中 ^ 是行首,$ 是行尾

    如果您的行假设为 3 列: aaa 113 bbbb

    cat file.txt|awk '{print $2}'|grep "^1133$"|wc -l

    确保您只查看特定列

    【讨论】:

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