模式内的Grep模式

时间:2019-06-21 11:52:24

标签: regex bash grep

cat sudo.txt |tr -d "[:blank:]"|grep '=.*[ALLroot].*/usr/bin/vim'

我要跟踪以下内容:

=(root)NOPASSWD:/usr/bin/vim
=(ALL)NOPASSWD:/usr/bin/vim
=NOPASSWD:/usr/bin/vim

但不是:

=(user)NOPASSWD:/usr/bin/find

2 个答案:

答案 0 :(得分:1)

给出数据,

grep -E '\bNOPASSWD:/usr/bin/vim\b' sudo.txt

如果选择还不够,请显示示例并解释缺少的要求。

答案 1 :(得分:0)

[ALLroot]匹配ALrot。请改用(ALL|root)

给出:

cat sudo.txt
=(root)NOPASSWD:/usr/bin/vim
=(ALL)NOPASSWD:/usr/bin/vim
=NOPASSWD:/usr/bin/vim
=(user)NOPASSWD:/usr/bin/find

grep -E '=(\((root|ALL)\))?.*/usr/bin/vim' sudo.txt
=(root)NOPASSWD:/usr/bin/vim
=(ALL)NOPASSWD:/usr/bin/vim
=NOPASSWD:/usr/bin/vim

说明:

选项-E:扩展模式

=                   # equal sign
(                   # start group
  \(                # opening parenthesis
    (root|ALL)      # root OR ALL
  \)                # closing parenthesis
)?                  # end group, optional
.*                  # 0 or more any character
/usr/bin/vim        # literally