如何使用 grep 在手册页中搜索选项?

8 command-line grep manpage

我想搜索特定的选项,比如-s-f-l在手册页和显示仅包含什么这些选项是做信息的结果。我尝试了这个命令,希望单引号可以绕过grep接收选项:

man --pager=cat some_man_page_here | grep '-option_here'
Run Code Online (Sandbox Code Playgroud)

我也试过,\grep给了我一个语法错误:

Usage: grep [OPTION]... PATTERNS [FILE]...
Try 'grep --help' for more information.
Run Code Online (Sandbox Code Playgroud)

我只是想知道是否有一种方法grep可以用来在联机帮助页中搜索选项。我目前正在使用终端顶部栏上的“查找”按钮,但我希​​望能够使用它grep来提高效率。

Wil*_*ens 8

这对你的情况有用吗?

$ man ls | grep -- '--a'
     -a, --all
     -A, --almost-all
     --author
Run Code Online (Sandbox Code Playgroud)

命令的更详细(希望更清晰)示例:

$ man shutdown | grep -- '-'
       shutdown - Halt, power-off or reboot the machine
       shutdown may be used to halt, power-off or reboot the machine.
       logged-in users before going down.
       --help
       -H, --halt
       -P, --poweroff
           Power-off the machine (the default).
       -r, --reboot
       -h
           Equivalent to --poweroff, unless --halt is specified.
       -k
           Do not halt, power-off, reboot, just write wall message.
       --no-wall
           Do not send wall message before halt, power-off, reboot.
       -c
       On success, 0 is returned, a non-zero failure code otherwise.
Run Code Online (Sandbox Code Playgroud)

编辑:

正如格伦杰克曼在下面评论的那样(非常有用):

并将结果缩小到仅以连字符开头的行:

grep '^[[:space:]]*-' – 
Run Code Online (Sandbox Code Playgroud)

测试运行:

$ man shutdown | grep -- '-' | grep '^[[:space:]]*-'
       --help
       -H, --halt
       -P, --poweroff
       -r, --reboot
       -h
       -k
Run Code Online (Sandbox Code Playgroud)

人们显然也可以在 Linux 中使用apropos

[+] 外部链接:

手册页的全文搜索 - 在 Unix SE

  • 并将结果缩小到仅以连字符开头的行:`grep '^[[:space:]]*-'` (4认同)
  • +1 也许有助于解释为什么 OP 的命令不起作用。 (2认同)

αғs*_*нιη 5

使用一个简单的函数,仅返回与命令开关相关的特定部分及其后续的简短描述,直接从其手册页:

\n
sman() {\n    man "${1}" \\\n    | grep -iozP -- "(?s)\\n+\\s+\\K\\Q${2}\\E.*?\\n*(?=\\n+\\s+-)"\n}\n
Run Code Online (Sandbox Code Playgroud)\n

称呼它sman <command-name> <switch>为:sman ls -A

\n
-a, --all\n              do not ignore entries starting with .\n -A, --almost-all\n              do not list implied . and ..\n
Run Code Online (Sandbox Code Playgroud)\n

说明(来自https://regex101.com/):

\n
\n
    \n
  • -i\xe2\x80\x94 启用不区分大小写的匹配
  • \n
  • -o\xe2\x80\x94 仅返回匹配的部分
  • \n
  • -z\xe2\x80\x94 将输入和输出数据视为行序列,每行以零字节(ASCII NUL 字符)而不是换行符结尾。
  • \n
  • -P\xe2\x80\x94 启用 PCRE
  • \n
\n
\n
    \n
  • (?s)将模式的其余部分与以下有效标志进行匹配:s
    \n s 修饰符\xe2\x80\x94 单行。点匹配换行符
  • \n
  • \\n+匹配换行符
    \n + 量词\xe2\x80\x94 匹配一次无限次,尽可能多的次数,根据需要返回(贪婪
  • \n
  • \\s+匹配任何空白字符
  • \n
  • \\K重置所报告比赛的起点。任何先前消耗的角色将不再包含在最终比赛中
  • \n
  • \\Q${2}\\E带引号的文字 \xe2\x80\x94 与扩展的$2字符字面匹配
  • \n
  • .*?匹配任何字符
    \n *? 量词\xe2\x80\x94 匹配零次无限次,尽可能少的次数,根据需要扩展(lazy
  • \n
  • \\n*匹配换行符
    \n * 量词\xe2\x80\x94 匹配零次无限次,尽可能多次,根据需要返回(贪婪
  • \n
  • (?=\\n+\\s+-)正向先行:断言下面的正则表达式匹配:
    \n\\n+匹配换行(换行)字符。
    \n\\s+匹配任何空白字符
    \n-匹配该字符-
  • \n
\n