Читать книгу Linux Bible - Christopher Negus - Страница 169

Searching in files with grep

Оглавление

If you want to search for files that contain a certain search term, you can use the grep command. With grep, you can search a single file or search a whole directory structure of files recursively.

When you search, you can have every line containing the term printed on your screen (standard output) or just list the names of the files that contain the search term. By default, grep searches text in a case-sensitive way, although you can do case-insensitive searches as well.

Instead of just searching files, you can also use grep to search standard output. So, if a command turns out lots of text and you want to find only lines that contain certain text, you can use grep to filter just want you want.

Here are some examples of grep command lines used to find text strings in one or more files:

 $ grep desktop /etc/services desktop-dna 2763/tcp # Desktop DNA desktop-dna 2763/udp # Desktop DNA $ grep -i desktop /etc/services sco-dtmgr 617/tcp # SCO Desktop Administration Server sco-dtmgr 617/udp # SCO Desktop Administration Server airsync 2175/tcp # Microsoft Desktop AirSync Protocol …

In the first example, a grep for the word desktop in the /etc/services file turned up two lines. Searching again, using the -i to be case-insensitive (as in the second example), there were 29 lines of text produced.

To search for lines that don't contain a selected text string, use the -v option. In the following example, all lines from the /etc/services file are displayed except those containing the text tcp (case-insensitive):

 $ grep -vi tcp /etc/services

To do recursive searches, use the -r option and a directory as an argument. The following example includes the -l option, which just lists files that include the search text, without showing the actual lines of text. That search turns up files that contain the text peerdns (case-insensitive).

 $ grep -rli peerdns /usr/share/doc/ /usr/share/doc/dnsmasq-2.66/setup.html /usr/share/doc/initscripts-9.49.17/sysconfig.txt …

The next example recursively searches the /etc/sysconfig directory for the term root. It lists every line in every file beneath the directory that contains that text. To make it easier to have the term root stand out on each line, the --color option is added. By default, the matched term appears in red.

 $ grep -ri --color root /etc/sysconfig/

To search the output of a command for a term, you can pipe the output to the grep command. In this example, I know that IP addresses are listed on output lines from the ip command that include the string inet, so I use grep to display just those lines:

 $ ip addr show | grep inet inet 127.0.0.1/8 scope host lo inet 192.168.1.231/24 brd 192.168.1.255 scope global wlan0

Linux Bible

Подняться наверх