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

我想在man页中搜索特定选项,如-s-f-l,并只显示包含这些选项信息的结果。我尝试了以下命令,希望单引号可以绕过grep接收选项:
man --pager=cat some_man_page_here | grep '-option_here'

我也尝试了\,但是grep给出了一个语法错误。
Usage: grep [OPTION]... PATTERNS [FILE]...
Try 'grep --help' for more information.

我只是想知道是否有办法使用 grep 在 manpage 中搜索选项。我目前在终端顶部栏使用 查找 按钮,但我希望能够使用 grep 来提高效率。


1你根本不需要用 grep。只需输入斜杠后面跟上要搜索的字符串即可。 - heynnema
我在帖子中写了一个答案,链接在关闭框中,以同时处理多个选项。 - user unknown
2个回答

这个对你来说行得通吗?
$ man ls | grep -- '--a'
     -a, --all
     -A, --almost-all
     --author

一个更详细(希望更清晰)的命令示例:
$ 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.

编辑:
正如格伦·杰克曼在下面评论中提到的(非常有用):

And to narrow down the results to just lines starting with a hyphen:

grep '^[[:space:]]*-' – 

测试运行:

$ man shutdown | grep -- '-' | grep '^[[:space:]]*-'
       --help
       -H, --halt
       -P, --poweroff
       -r, --reboot
       -h
       -k

显然,在Linux中也可以使用apropos。
[+] 外部链接:
[link1:man页面的全文搜索 - 在Unix SE上]

4并且为了将结果缩小到只有以连字符开头的行:grep '^[[:space:]]*-' - glenn jackman
1哦,谢谢,这对我有用! - user1131566
@glennjackman 真令人印象深刻!谢谢你的夸奖!我已经编辑了我的回答,包括了你的评论。// 致意 - William Martens
2或许解释一下为什么OP的命令无效可能会有帮助。 - schrodingerscatcuriosity

使用一个简单的函数来仅返回与命令开关及其后面的简短描述相关的特定部分,而且直接从它们的 man 页面中获取。
sman() {
    man "${1}" \
    | grep -iozP -- "(?s)\n+\s+\K\Q${2}\E.*?\n*(?=\n+\s+-)"
}

叫它sman <command-name> <switch>,就像这样:sman ls -A
-a, --all
              do not ignore entries starting with .
 -A, --almost-all
              do not list implied . and ..

解释(来自https://regex101.com/):
  • -i — 启用不区分大小写匹配。
  • -o — 仅返回匹配部分。
  • -z — 将输入和输出数据视为一系列以零字节(ASCII NUL字符)而不是换行符终止的行序列。
  • -P — 启用PCRE。

  • (?s) 匹配模式的其余部分,具有以下有效标志:s
    s 修饰符 — 单行模式。点匹配换行符
  • \n+ 匹配换行符
    + 量词 — 匹配 一个无限多个 次,尽可能多次地匹配,根据需要回溯(贪婪模式)
  • \s+ 匹配任何空白字符
  • \K 重置报告匹配的起始点。之前已消耗的字符不再包含在最终匹配中
  • \Q${2}\E 引用字面值 — 字面上匹配扩展的 $2 字符
  • .*? 匹配任何字符
    *? 量词 — 匹配 无限多个 次,尽可能少次地匹配,根据需要扩展(惰性模式)
  • \n* 匹配换行符
    * 量词 — 匹配 无限多个 次,尽可能多次地匹配,根据需要回溯(贪婪模式)
  • (?=\n+\s+-) 正向先行断言:断言以下正则表达式匹配:
    \n+ 匹配换行符
    \s+ 匹配任何空白字符
    - 字面上匹配字符 -