На этот вопрос уже есть ответ здесь:
Команда man
вызывает хорошее руководство для многих программ, но как использовать его более эффективно? Например, man gcc
выводит:
NAME
gcc - GNU project C and C++ compiler
SYNOPSIS
gcc [-c|-S|-E] [-std=standard]
[-g] [-pg] [-Olevel]
[-Wwarn...] [-Wpedantic]
[-Idir...] [-Ldir...]
[-Dmacro[=defn]...] [-Umacro]
[-foption...] [-mmachine-option...]
[-o outfile] [@file] infile...
Only the most useful options are listed here; see below for the
remainder. g++ accepts mostly the same options as gcc.
....
many text
Но что если мне нужна только часть руководства? Как лучше всего перейти к разделу, где описывается, например, -Idir
?
man
, нажав / kbd>, и строка поиска man
по умолчанию использует средство просмотра less
. Вы можете выполнить поиск в less
, нажав / kbd> (косая черта), а затем добавьте строку поиска, в вашем примере -Idir
GCC(1) GNU GCC(1)
NAME
gcc - GNU project C and C++ compiler
SYNOPSIS
gcc [-c|-S|-E] [-std=standard]
[-g] [-pg] [-Olevel]
[-Wwarn...] [-Wpedantic]
[-Idir...] [-Ldir...]
[-Dmacro[=defn]...] [-Umacro]
[-foption...] [-mmachine-option...]
[-o outfile] [@file] infile...
Only the most useful options are listed here; see below for the
remainder. g++ accepts mostly the same options as gcc.
DESCRIPTION
When you invoke GCC, it normally does preprocessing, compilation,
assembly and linking. The "overall options" allow you to stop this
process at an intermediate stage. For example, the -c option says not
to run the linker. Then the output consists of object files output by
the assembler.
/-Idir
Нажмите Enter < / kbd> и получите первое совпадение.
Нажмите / kbd> (косая черта) и снова нажмите клавишу Enter kbd>, повторяйте, пока не найдете нужный раздел. Вы также можете нажать n kbd> для следующего матча.
-Idir
Add the directory dir to the head of the list of directories to be
searched for header files. This can be used to override a system
header file, substituting your own version, since these directories
are searched before the system header file directories. However,
you should not use this option to add directories that contain
vendor-supplied system header files (use -isystem for that). If
you use more than one -I option, the directories are scanned in
left-to-right order; the standard system directories come after.
If a standard system include directory, or a directory specified
with -isystem, is also specified with -I, the -I option is ignored.
The directory is still searched but as a system directory at its
normal position in the system include chain. This is to ensure
that GCC's procedure to fix buggy system headers and the ordering
for the "include_next" directive are not inadvertently changed. If
you really need to change the search order for system directories,
use the -nostdinc and/or -isystem options.
-iplugindir=dir
Set the directory to search for plugins that are passed by
-fplugin=name instead of -fplugin=path/name.so. This option is not
meant to be used by the user, but only passed by the driver.
Manual page gcc(1) line 10179 (press h for help or q to quit)
SUMMARY OF LESS COMMANDS
Commands marked with * may be preceded by a number, N.
Notes in parentheses indicate the behavior if N is given.
A key preceded by a caret indicates the Ctrl key; thus ^K is ctrl-K.
h H Display this help.
q :q Q :Q ZZ Exit.
---------------------------------------------------------------------------
MOVING
e ^E j ^N CR * Forward one line (or N lines).
y ^Y k ^K ^P * Backward one line (or N lines).
f ^F ^V SPACE * Forward one window (or N lines).
b ^B ESC-v * Backward one window (or N lines).
z * Forward one window (and set window to N).
w * Backward one window (and set window to N).
ESC-SPACE * Forward one window, but don't stop at end-of-file.
d ^D * Forward one half-window (and set half-window to N).
u ^U * Backward one half-window (and set half-window to N).
ESC-) RightArrow * Left one half screen width (or N positions).
ESC-( LeftArrow * Right one half screen width (or N positions).
F Forward forever; like "tail -f".
ESC-F Like F but stop when search pattern is found.
r ^R ^L Repaint screen.
R Repaint screen, discarding buffered input.
---------------------------------------------------
Default "window" is the screen height.
Default "half-window" is half of the screen height.
---------------------------------------------------------------------------
SEARCHING
/pattern * Search forward for (N-th) matching line.
?pattern * Search backward for (N-th) matching line.
n * Repeat previous search (for N-th occurrence).
N * Repeat previous search in reverse direction.
ESC-n * Repeat previous search, spanning files.
ESC-N * Repeat previous search, reverse dir. & spanning files.
ESC-u Undo (toggle) search highlighting.
&pattern * Display only matching lines
---------------------------------------------------
A search pattern may be preceded by one or more of:
^N or ! Search for NON-matching lines.
^E or * Search multiple files (pass thru END OF FILE).
^F or @ Start search at FIRST file (for /) or last file (for ?).
^K Highlight matches, but don't move (KEEP position).
^R Don't use REGULAR EXPRESSIONS.
---------------------------------------------------------------------------
HELP -- Press RETURN for more, or q when done
Подробнее о «инструментах помощи» вы можете узнать по следующей ссылке
Я не могу улучшить ответ Wildcard , когда я задал тот же вопрос в Unix & amp; Linux Q & A.
Если вы хотите
grep
получить результатыman <program>
для шаблона, начинающегося с дефиса, используйте--
перед указанным шаблоном. Пример использованияman find
:man find | grep -- -type
Если вам нужна дополнительная информация, например, весь раздел, описывающий опцию, вы можете попробовать использовать
sed
:$ man find | sed -n '/-mindepth/,/^$/p' -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). -mindepth 1 means process all files except the command line arguments.
Однако, это не сработает для каждой опции, которую вы можете искать. Например:
$ man find | sed -n '/^[[:space:]]*-type/,/^$/p' -type c File is of type c:
Не очень полезно. Хуже того, для некоторых вариантов вы можете быть введены в заблуждение, полагая, что прочитали бы весь текст об этом варианте, хотя на самом деле это не так. Например, при поиске
-delete
опускается очень важное ПРЕДУПРЕЖДЕНИЕ, содержащееся в втором абзаце под этим заголовком.
Я рекомендую использовать стандартный вызов
man
с установленной переменной средыLESS
. Я часто использую его в своих ответах на этом сайте.LESS='+/^[[:space:]]*-type' man find
Чтобы узнать больше о том, как это работает, см .:
LESS='+/^[[:space:]]*LESS ' man less LESS='+/\+cmd' man less LESS='+/\/' man less
Если вы просто хотите быстро и в интерактивном режиме найти эту опцию на странице man, научитесь использовать
less
возможности поиска. А также см .:
Я хотел бы ответить на него самым простым способом.
После того, как вы откроете man-страницу для пакета, используя man <package>
, вы можете использовать утилиту поиска, чтобы найти детали конкретных опций, используя /<option>
, например, чтобы проверить детали опции -r, используйте /-r
.
Когда вы просматриваете страницы руководства и выполняете поиск, нажимая / kbd>, less
фактически обрабатывает ваш шаблон поиска как регулярное выражение . При поиске параметров командной строки очень полезно добавить к ним \b
, что соответствует границе слова . Это часто пропускает много текста, который в противном случае соответствовал бы, но это не то, что я ищу (или что, в любом случае, не то, что я хочу прочитать первым).
Например, для поиска опции -I
вы можете набрать:
/-I\b
/
сообщает less
, что вы хотите искать, как уже упоминали другие ( см. Ответ MIB ). Вы бы написали ?
вместо /
, если бы вы хотели, чтобы ваш поиск шел вверх по странице руководства, а не вниз. -I
- это текст, который вы ищете. \b
соответствует границе между символом слова (A-Z
, a-z
или _
) и несловесным символом, или между символом слова и самым началом или концом текста, в котором это происходит. Возможно, вам все еще нужно найти последующие совпадения. Для этого нажмите n kbd>. Чтобы вернуться к предыдущим матчам, нажмите Shift kbd> + n kbd>.
Например, в случае поиска -I
в справочной странице gcc
я обнаружил, что -I
сопоставлялся шесть раз до того поиска, которое я искал, где опция -I
была фактически задокументирована. Напротив, -I\b
сопоставлялось только один раз до этого совпадения.
Если вы предпочитаете, вы можете использовать \>
вместо \b
. \>
соответствует только концу слова (где «слово» - это один или несколько символов слова, как определено выше). Если вы хотите сопоставить начало слова, вы можете использовать \<
. Обратите внимание, однако, что не получается написать что-то вроде \<-I
для соответствия опции -I
, потому что \<
не сможет соответствовать пробелу, за которым следует -
.