Search man page linux

How to search Linux man pages (e.g. with grep)

I’m looking for information on the -X option of curl . However, the documentation is quite lengthy and I have to scroll down for quite a long time to get to this option. Instead, I’d like to do something like

to get the line containing «-X». (I would also do this in conjunction with the option -A 10 to get the 10 lines after the match). However, if I try this I get

grep: option requires an argument -- 'X' Usage: grep [OPTION]. PATTERN [FILE]. Try 'grep --help' for more information. 

Any ideas on how to use grep together with man , or more generally on how to search man pages for specific lines?

3 Answers 3

You have to tell grep that -X is not an option, but the pattern to look for:

— indicates the end of options. Without it, grep thinks that -X is an option.

Alternatively, you can use -e to indicate that what follows is a pattern:

If you want to see the complete man page but skip directly to the first occurrence of -X , you can use a command line option to less :

Typing N repeatedly then takes you to the following occurrences.

I did man curl | grep -a 20 — ‘-X’ together with the -a 20 option to read the first 20 lines below each result. This allowed me to quickly find the documentation on the -X option without having to scroll down too much.

@KurtPeek: you probably mean -A , because -a simply states that a binary files should be processed as text as well.

In MacOs, I want to get doc about find with arg -type , so I input man find | grep — ‘-type’ , but return this two pseudo-types, «local» and «rdonly». The former matches find / -type f -exec echo <> \;

On most Linux systems, the default pager used by man is less .

If that is the case, you can search in a man page using the / (slash) key followed by a query (here -X ) and finally hit ENTER . It will highlight all cases of -X . It is of course possible that the first «hit» is not the one you want. In that case you can hit N to go to the Next hit and so browse through the entire document. In case you have jumped too far, you can use Shift + N to jump back to the previous hit.

This is not really an answer to the question how to handle this with grep , but it is simply a way to efficiently search in man .

Читайте также:  Linux shared library naming

You can read the man page of less ( man less ) for further tricks on how to effectively use less to improve your experience with man pages.

man will implicitly open in less if you have it installed. So maybe you could read man page for less .

less actually supports search on it’s own. Just press / and write what you wanna search and enter . Use n to skip to next occurrence and N for previous.

Be careful when stating man will implicitly open in less . On most systems this is the case but some Linux distros might opt for another one and furthermore a user can set the $PAGER or $MANPAGER variables and alter the pager that is used.

Источник

Man-страницы в Linux. Как пользоваться. Установка

Man страницы в Linux

При работе в Linux иногда требуется чтение документации, руководств или help’ов. В Linux есть отличная документация, которая размещена в Man-страницах.

Что такое Man-страницы

Man-страницы (от слова manualруководство) — это целая библиотека в системе Linux, содержащая руководства по командам, утилитам, программированию и другим областям системы и не только.

Как открыть Man-страницы

Для чтения Man-страниц предназначена команда man .

Чтобы получить руководство по использованию какой-либо команды нужно выполнить команду:

Например, чтобы вывести руководство по команде wget, нужно выполнить команду:

man wget

Синтаксис команды man

В общем виде синтаксис команды man следующий:

Разделы

Man-страницы разделены по тематикам на разделы (на секции). Каждый раздел имеет свой номер. Всего существует 8 основных разделов.

Если вы не указали раздел, при выполнении команды man , то сначала будет выполнен поиск руководства в первом разделе, если его там нет, то во втором и так далее.

Например, откроем руководство по команде sleep. В данном случае будет использоваться первый раздел.

man sleep

А теперь получим справку по библиотечному вызову sleep языка программирования C (раздел 3):

man 3 sleep

Ниже представлена таблица с номерами разделов и их назначением (тематикой).

Номер
раздела
Описание
1 Основные команды.
2 Системные вызовы.
3 Библиотечные функции, включая стандартную библиотеку языка C.
4 Специальные файлы (обычно устройства из /dev ) и драйвера.
5 Форматы файлов и соглашения.
6 Игры и скринсейверы.
7 Разное.
8 Команды системного администрирования и демоны.

Для указания ссылок на Man-страницы часто используют следующую запись: имя(раздел) . Например, aporopos(1) , less(1) , exit(3) .

Поиск Man-страниц

Самая полезная опция команды man , это опция -k .

-k — поиск Man-страниц. Выводит список Man-страниц, в которых встречается искомый запрос.

Горячие клавиши и поиск внутри Man-страницы

Вверх , Вниз , Enter — просмотр (прокрутка) Man-страницы.
PgUb , PgDn , Пробел — постраничное пролистывание.

/ — поиск внутри страницы. Нажимаете клавишу / , при этом внизу появляется строка для ввода текста. Вводите текст, который вы хотите найти, и нажимаете Enter .
? — поиск в обратном направлении (снизу вверх). Аналогично нужно ввести текст для поиска и нажать Enter .
n — переход к следующему вхождению.
Shift+n — переход к предыдущему вхождению.
& — поиск внутри страницы, но вместо подсвечивания результатов, вывести только строки, где было найдено искомое слово.

h — открыть справку по командам и горячим клавишам. Чтобы закрыть справку, используется клавиша q .

Установка Man-страниц

Как правило, базовые man-страницы обычно всегда установлены в дистрибутивах Linux, но иногда их нужно устанавливать самостоятельно. Для установки Man-страниц выполните следующие команды.
Для Ubuntu:

sudo apt install man-db manpages
yum install man man-pages man-db

Для установки Man-страниц, содержащих описание библиотечных функций языка программирования C, выполните следующие команды.
Для Ubuntu:

sudo apt install manpages-dev manpages-posix-dev

Источник

man Command in Linux with Examples

The man command is a built-in manual for using Linux commands. It allows users to view the reference manuals of a command or utility run in the terminal. The man page (short for manual page) includes a command description, applicable options, flags, examples, and other informative sections.

In this tutorial, you will learn to use the man command in Linux.

How to use the man command in Linux.

  • A machine running Linux
  • Access to the command line
  • An account with root privileges

Linux man Command Syntax

The basic man command syntax is:

man [option] [section number] [command name]
  • option – the search result output.
  • section number – the section in which to look for the man page.
  • command name – the name of the command which man page you want to see.

By default, man looks in all the available sections of the manual and shows the first match (even if the page exists in several sections). Providing a section number instructs the man command to look in a specific section.

There are nine sections of the manual:

1. General commands: Commands used in the terminal.

2. System calls: Functions the kernel provides.

3. Library functions: Functions in program libraries.

4. Special files: Usually devices found in /dev and related drivers.

5. File formats and conventions: File formats like etc/passwd.

6. Games: Descriptions of commands that display database quotes.

7. Miscellaneous: Various descriptions, including macro packages and conventions, boot parameters, and others.

8. System administration commands: Commands mostly reserved for root.

9. Kernel Routines: Information about internal kernel operations.

How to Use man in Linux

In the terminal window, type man followed by the Linux command name which man page you want to see.

The output is lengthy. Use the mouse scroll wheel, the up and down arrow keys, or the PgDn and PgUp keys to navigate through it.

After running the man command, press H to see the help section and a table of possible keystrokes for navigating the output.

To exit, press Q.

The output of the command displays the available man page headings for the specified command.

The list of possible headings includes:

  • Name: The name of the command.
  • Synopsis: The command’s syntax.
  • Configuration: Configuration details for a device.
  • Description: A description of the command.
  • Examples: Several examples demonstrating the use of the command.
  • Defaults: The default functions of the command and how they can be overridden.
  • Options: A list of options and flags that the command accepts.
  • Exit Status: A list of possible exit status values for the command.
  • Environment: A list and description of environment variables that affect the command.
  • Files: A list of files used by the command.
  • See also: Commands related to the described topic.
  • Authors: The people who wrote or maintain the command.
  • History: Command development history.
  • Notes: Various notes, including permissions required, dependencies, etc.
  • Bugs: Any known issues in this program version.

Note: Pages may contain more or fewer headings depending on the man page contents.

Look for man Pages

The -f option displays all man pages that match the specified command name and states the sections in which the given command is present.

Look for man pages in Linux.

The output is a list of results that match the search criteria. With multiple matches, the number next to the search result indicates the section.

Display man Pages From Specific Sections

To display the page from a specific section of a manual, use the syntax:

man [section number] [command name]

See a man page from a specific section.

The output shows only the page from section 3 of the manual.

Display man Pages in a Browser

Man pages are long and sometimes difficult to scroll through to find the information you need. The man command allows users to display man pages in a browser to find information easily.

To do so, follow these steps:

1. Make sure the groff package is installed. Run:

sudo apt-get install groff

2. Before calling the man command, select a default browser. Run:

To use a different browser, replace firefox with google-chrome , chromium-browser , or any other browser.

3. Use the -H option to read the man page in a browser of your choice:

Man pages can be read in browsers using the -H option.

The -H option instructs groff to produce an HTML output and displays that output in a browser.

Display man Pages and Print Short Descriptions

The -f option allows users to look up the man pages and prints out short descriptions of the specified command in the terminal. The syntax is:

See a short man page description.

Display All man Pages

The -a attribute allows users to display all available intro manual pages contained in each section, one at a time.

Display all man pages using the -a option.

Quit between successive displays or skip through them using Ctrl+C or Ctrl+D, respectively.

Search by Considering Input as a Regular Expression

The -k option allows users to search the short command descriptions and manual page names for a specified keyword as a regular expression. The output shows any available matches.

Conduct a search in man considering input as a regular expression.

Display Location of man Pages

The -w attribute shows the location of the manual page of the specified command. Adding the -a option prints out the locations of all files matching the keyword.

See the location of man pages using the -w option.

In this example, we used the -a option to see the locations of all associated man pages.

Additionally, using the -W option displays the location of the preformatted cat file. With the -a option, it prints out the locations of all preformatted cat files matching the keyword.

Enable Case-Sensitivity

To search for manual pages using case-sensitivity, use the -I option. The syntax is:

The man default setting is to ignore case when looking up manual pages. To go back to default settings and ignore case, use the -i option.

Search for man pages with case sensitivity enabled.

You now know how to use the man command in Linux. Use the command to see user manuals for Linux commands, search for a specific keyword, or see all the entries in the manual.

To learn how can you search all man pages using known details as a search term, make sure to read our article apropos Linux command.

For more uses, refer to our article and find out how can man command review the complete manual for Expect.

Источник

Оцените статью
Adblock
detector