grep字符串,包括正斜线作为单词的一部分 [英] grep string including forward slash as part of word

查看:94
本文介绍了grep字符串,包括正斜线作为单词的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将/视为word和grep完全匹配的一部分?

How to treat / as part of word and grep exact match?

$ echo "aa/bb/cc dd/ee/ff" | grep -w aa/bb
aa/bb/cc dd/ee/ff
$ 

我希望grep匹配整个字符串,而/无例外. 在上面的示例中,我不希望它匹配aa/bb/cc字符串,但是仅当存在任何aa/bb

I want grep to match the whole string without exception to /. In the above example, I don't want it to match aa/bb/cc string, but match only if there is any aa/bb

预期输出:

$ echo "aa/bb/cc dd/ee/ff" | grep <options??> aa/bb
$ <empty>
$ echo "aa/bb dd/ee/ff" | grep <options??> aa/bb
aa/bb dd/ee/ff
$ echo "kk/ll aa/bb dd/ee/ff" | grep <options??> aa/bb
kk/ll aa/bb dd/ee/ff
$ echo "kk/ll dd/ee/ff aa/bb" | grep <options??> aa/bb
kk/ll dd/ee/ff aa/bb    
$ echo "kk/ll dd/ee/ff aa/bb/cc" | grep <options??> aa/bb
$ <empty>
$ echo "kk/ll dd/ee/ff a-aa/bb" | grep <options??> aa/bb
$ <empty>

推荐答案

grep 方法:

grep approach:

echo "aa/bb/cc aa/bb dd/ee/ff" | grep -P '(?:^|\s)aa/bb(?=\s|$)'
aa/bb/cc aa/bb dd/ee/ff


echo "aa/bb/cc aa/bb dd/ee/ff" | grep -P '(?:^|\s)aa/bb(?=\s|$)'
<empty>


  • -P-Perl正则表达式
  • (?:^|\s)aa/bb(?=\s|$):
    • (?:^|\s)-具有捕获组的非捕获组,以匹配字符串^或空格字符\s
    • 的开头
    • aa/bb-逐字匹配aa/bb序列
    • (?=\s|$)-前瞻性肯定断言,包含与空白字符\s或字符串$
    • 末尾匹配的替代组


      • -P - perl regex
      • (?:^|\s)aa/bb(?=\s|$):
        • (?:^|\s) - non-captured group with alternation group to match either the start of the string ^ or whitespace character \s
        • aa/bb - match aa/bb sequence literally
        • (?=\s|$) - lookahead positive assertion containing alternation group to match either whitespace character \s or the end of the string $
        • 这篇关于grep字符串,包括正斜线作为单词的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆