How to use grep to search for options in a man page?

Would this work in your case?

$ man ls | grep -- '--a'
     -a, --all
     -A, --almost-all
     --author

A more detailed (hopefully clearer) example of the command:

$ 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.

Edit:

As glenn jackman commented below (very useful):

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

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

Test run:

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

working with a simple function to return only the specific part related to the command's switches and their followed short-description in addition, from their man-pages directly:

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

Call it sman <command-name> <switch> like: sman ls -A

-a, --all
              do not ignore entries starting with .
 -A, --almost-all
              do not list implied . and ..

Explanations (from https://regex101.com/):


  • -i — enable case-insensitive match
  • -o — return only matched part
  • -z — Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline.
  • -P — enables PCRE

  • (?s) match the remainder of the pattern with the following effective flags: s
    s modifier — single line. Dot matches newline characters
  • \n+ matches a line-feed (newline) character
    + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
  • \s+ matches any whitespace character
  • \K resets the starting point of the reported match. Any previously consumed characters are no longer included in the final match
  • \Q${2}\E Quoted Literals — matches the expanded $2 characters literally
  • .*? matches any character
    *? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
  • \n* matches a line-feed (newline) character
    * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
  • (?=\n+\s+-) Positive Lookahead: Assert that the Regex below matches:
    \n+ matches a line-feed (newline) character.
    \s+ matches any whitespace character
    - matches the character - literally.