【问题标题】:Word(s) exclusion in pattern without using -v option in (e)grep在 (e)grep 中不使用 -v 选项的模式中排除单词
【发布时间】:2019-05-01 17:33:43
【问题描述】:

是否可以在不使用 -v 选项的情况下仅使用模式排除 (e)grep 中的确切单词。例如,由于 () 将模式或精确字符串 () 分组,我认为 egrep [^(main)] 将匹配没有精确单词 main 的子字符串,但结果是它排除了字母 m,a,i,n。我还在学习 bash 中的正则表达式。

【问题讨论】:

标签: regex linux grep


【解决方案1】:

您可以使用此否定前瞻正则表达式来拒绝包含main 作为整个单词的行,而不必使用-v

grep -P '^(?!.*\bmain\b).*$' bash.txt

这里,-P 启用 Perl regular expression

前面是一个名为 bash.txt 的文件的内容,

hello 123
hello world
hello main world
some main text
some mainly text

在运行上述命令时,它会打印此输出,

hello 123
hello world
some mainly text

【讨论】:

    【解决方案2】:

    原因

    egrep [^(main)] 不包括字母 m,a,i,n。

    是 [^(main)] 匹配不包含在括号内的单个字符,其中不仅排除了 m,a,i,n,还排除了 ( 和 )。你可以找到这个功能的正确用法here

    其实已经有类似StackOverflow的问题了。它有几种形式的负前瞻。 ^((?!main).)*$ 可能是满足您需求的其中之一。

    【讨论】:

      【解决方案3】:

      idk 是否是你想要的,但借用 @Pushpesh's example 然后使用任何 POSIX awk:

      $ awk '!/(^|[^[:alpha:]])main([^[:alpha:]]|$)/' file
      hello 123
      hello world
      some mainly text
      

      或使用 GNU 工具进行字边界:

      $ awk '!/\<main\>/' file
      hello 123
      hello world
      some mainly text
      
      $ sed '/\<main\>/d' file
      hello 123
      hello world
      some mainly text
      

      【讨论】:

        猜你喜欢
        • 2018-10-17
        • 2016-11-09
        • 1970-01-01
        • 1970-01-01
        • 2012-12-02
        • 2011-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多