如何使用 grep 搜索以连字符 (-) 开头的模式?

RNA*_*RNA 5 grep

sudo find / -name "*" | xargs grep -sn --color=auto "-j"
Run Code Online (Sandbox Code Playgroud)

上面的命令返回如下:

grep: invalid option -- 'j'
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.
...
Run Code Online (Sandbox Code Playgroud)

如何搜索字符串-j

Rad*_*anu 6

在您的情况下,"-j"被解释grep为参数/选项,而不是搜索模式,即使您引用了它。要使其成为您要搜索的模式,只需使用-e选项:

sudo find / -name "*" | xargs grep -sn --color=auto -e "-j"
Run Code Online (Sandbox Code Playgroud)

甚至:

sudo find / -name "*" | xargs grep -sn --color=auto -e -j
Run Code Online (Sandbox Code Playgroud)

-e参数/选项意味着下一个参数是模式。这是来自man grep

   -e PATTERN, --regexp=PATTERN
          Use  PATTERN  as  the  pattern.   This  can  be  used to specify
          multiple search patterns, or to protect a pattern beginning with
          a hyphen (-).  (-e is specified by POSIX.)
Run Code Online (Sandbox Code Playgroud)

其他方法: