【问题标题】:Grep exact word UNIXgrep 确切的单词 UNIX
【发布时间】:2018-02-04 11:34:48
【问题描述】:

我有一个文件,我想从该文件中 grep 一个特定的单词。我正在使用 MobaXterm。例如,我想 grep 单词 test-common 并且在我的文件中

 1. Version: 1.0.0    test-common Author Created Path   
 2. Version: 1.0.0    test-common-config   Author   Created Path    
 3. Version: 1.0.0    unit-test-common   Author   Created Path   
 4. Version: 1.0.0    unit-test-common-config   Author   Created Path  

我试过了:

  • grep test-common file
  • grep "\\< test-common \\>" file(不返回任何东西)
  • grep -w test-common file
  • grep -w "test-common " file
  • grep -r "\btest-common\b" file(不返回任何内容)
  • grep -sw test-common file(不工作)
  • grep -o test-common file(不工作)
  • grep \\< bil-common \\>文件

^bil-commonbil-common$ 也不起作用。

对于我有结果的命令,结果是:

test-common
test-common-config

这不是我想要的。任何帮助表示赞赏。

【问题讨论】:

  • 结果如你所愿,不是吗?
  • 不,我只想得到 test-common 而不是 test-common 和 test-common-config
  • 如果该行没有其他字符,则可以进行整行匹配 - grep -x 'test-common' file
  • 每一行还有其他信息。但为了不发布任何不必要的信息,我只写了我想找到的内容
  • @isovitis 用于文本处理,每个字符都可能变得重要...建议添加完整的示例输入行并显示预期输出.. 到目前为止,看到您的示例和 cmets,我无法理解您的用例

标签: linux bash shell unix grep


【解决方案1】:

你可以这样做:

grep -E '(^|\s+)test-common(?=\s|$)' file

这匹配“test-common”,后面只有一个空格或行尾,前面有一个或多个空格,或行首。

【讨论】:

  • @isovitis 您的问题被标记为 bash 和 linux,Linux 上使用的 GNU grep 几十年来一直支持 -E 选项。您能否更新问题以提供有关您的设置的更多详细信息,例如提一下你是在 BusyBox 还是其他非标准环境下运行命令?
  • @isovitis 我不确定那里是否支持它。你有egrep 可用吗?
  • 仍然不可用。
  • @Maroun lookarounds not available with BRE/ERE...grep -P 可以工作,但 OP 提到不可用... imo,OP 没有提供正确的样本输入/输出...我认为 OP 想要打印整行,在这种情况下不需要环视...如果需要,可以使用 [[:space:]] 代替 \s
  • @Maroun,阅读 grep 文档:不支持 ERE 模式下的正则表达式环视 -E
【解决方案2】:

1)我认为最简单的方法就是:
前后添加字符串空间(以防你知道它在字符串的中间)

       grep " string " file

2)如果所有答案都不起作用,我会检查 grep 是否被您命名:

   witch grep

或添加

\ 在 grep 之前签名,确保使用 unix grep

      \grep " string " file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多