【问题标题】:Grep: First word in line that begins with ? and ends with?Grep:以 ? 开头的第一个单词并以?
【发布时间】:2014-01-14 22:01:42
【问题描述】:

我正在尝试执行一个 grep 命令来查找文件中第一个单词以“as”开头且第一个单词也以“ng”结尾的所有行

我将如何使用 grep 执行此操作?

【问题讨论】:

    标签: grep


    【解决方案1】:

    这应该差不多了:

    $ grep '^as\w*ng\b' file
    

    正则解释:

    ^    # Matches start of the line
    as   # Matches literal string as
    \w   # Matches characters in word class
    *    # Quantifies \w to match either zero or more
    ng   # Matches literal string ng
    \b   # Matches word boundary
    

    可能错过了奇怪的角落案例。

    如果您只想打印匹配的单词而不是整行,请使用-o 选项:

    $ grep -o '^as\w*ng\b' file
    

    阅读man grep 了解有关可用选项的所有信息。

    【讨论】:

    • 看起来和我建议的格式一样,但解释更清楚。
    【解决方案2】:

    我很确定这应该可行:

    grep "^as[a-zA-Z]*ng\b" <filename>
    

    如果不从实际输入文件中查看样本,很难说。

    【讨论】:

    • .* 将过于贪婪和过度匹配,即as as ng
    • 此命令在运行后似乎会查看整行,而不是第一个单词。嗯。
    • @sudo_O 非常正确,搞砸了。
    【解决方案3】:

    sudo 已经介绍的很好了,但是我想再扔一个更简单的:

    grep -i '^as[^ ]*ng\b' <file>
    
    -i     to make grep case-insensitive
    [^ ]*  matches zero or more of any character, except a space
    

    【讨论】:

      【解决方案4】:

      ^ 查找“一行中的第一个字符”,因此您可以使用以下命令进行搜索:

      grep '^as' [file]
      

      \w 匹配一个单词字符,所以\w* 将匹配任意数量的单词字符:

      grep '^as\w*' [file]
      

      \b 表示“单词和空格之间的边界”,您可以使用它来确保匹配单词末尾的“ng”字母,而不仅仅是在中间的某个位置:

      grep '^as\w*ng\b' [file]
      

      如果您选择省略 [file],只需将您的文件通过管道传输到其中:

      cat [file] | grep '^as\w*ng\b'
      

      echo [some text here] | grep '^as\w*ng\b'
      

      这就是你要找的吗?

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2018-07-05
      • 2015-11-28
      相关资源
      最近更新 更多