Linux grep command usage

Source: Internet
Author: User

1. grep Introduction
Grep (Global Search Regular Expression (re) and print out

Line is a powerful text search tool that can use regular expressions to search for text and print matching rows. UNIX grep Family Package
Including grep, egrep, and fgrep. The commands of egrep and fgrep are only slightly different from those of grep. Egrep is an extension of grep and supports more re metacharacters,
Fgrep is fixed grep or fast
Grep, which regards all letters as words. That is to say, the metacharacters in the regular expression represent their literal meanings and are no longer special. Linux uses GNU grep. Function
Stronger. You can use the egrep and fgrep functions through the-G,-E,-F command line options.

Grep works like this. it searches for string templates in one or more files. If the template contains spaces, it must be referenced. All strings after the template are treated as file names. The search result is sent to the screen without affecting the content of the original file.

Grep can be used in shell scripts because grep returns a status value to indicate the search status. If the template search is successful, 0 is returned. If the search is unsuccessful, 1 is returned, if the searched file does not exist, 2 is returned. We can use these return values to automate text processing.
Function Description: Find the matching strings in the file.

Syntax: grep [-abcefghhillnqrsvvwxy] [-A] [-B] [-C] [-D] [-E] [-F] [-- help] [template style] [file or directory...]
Note:
The grep command is used to find files whose content contains the specified template style. If the content of a file conforms to the specified template style, the default grep command displays the column containing the template style. If no file name is specified or the given file name is "-", the grep command reads data from the standard input device.

Parameters:
-A or -- text do not ignore binary data.
-A or -- After-context = displays the content after the column except the column that conforms to the template style.
-B or -- byte-offset indicates the first character of the column before displaying the column that conforms to the template style.
-B or -- before-context = except for displaying the column that conforms to the template style and the content before this column.
-C or -- count is used to calculate the number of columns that conform to the template style.
-C or -- Context = or-display the content before and after the column except the column that conforms to the template style.
-D or -- directories = this parameter is required when you specify a directory rather than a file to be searched. Otherwise, the grep command returns information and stops the operation.
-E or -- Regexp = Specify a string as the template style for searching the file content.
-E or -- extended-Regexp use the template style as an extended normal notation.
-F or -- file = specifies the template file, whose content contains one or more template styles, so that grep can find the content of the file that meets the template conditions. The format is one template style for each column.
-F or -- fixed-Regexp treats the template style as a list of fixed strings.
-G or -- Basic-Regexp treats the template style as a normal notation.
-H or -- no-filename does not indicate the file name of the column before displaying the column that conforms to the template style.
-H or -- With-filename indicates the file name of the column before displaying the column that conforms to the template style.
-I or -- ignore-case ignore the differences in case of characters.
-L or -- file-with-Matches: lists the names of files whose content conforms to the specified template style.
-L or -- files-without-match lists the names of files whose contents do not conform to the specified template style.
-N or -- line-number indicates the number of columns in the column before displaying the column that conforms to the template style.
-Q or -- quiet or -- silent does not display any information.
-R or -- Recursive this parameter has the same effect as the specified "-D recurse" parameter.
-S or -- no-messages Do Not Display error messages.
-V or -- revert-match reverse lookup.
-V or -- version displays version information.
-W or -- word-Regexp only displays columns that match the full word.
-X or -- line-Regexp only displays columns that match the full column.
-Y: the effect of this parameter is the same as that of the specified "-I" parameter.
-- Help Online Help.

2. grep Regular Expression metacharacter set (basic set)

^
For example, '^ grep' matches all rows starting with grep.
$
For example, 'grep $ 'matches all rows ending with grep.
Match a non-linefeed character, for example, 'gr. P' matches gr followed by any character and then p.
*
Match zero or multiple previous characters, such as '* grep'. Match All one or more spaces followed by grep rows. . * Represents any character.
[]
Matches a character in a specified range, for example, '[Gg] rep' matches grep and grep.
[^]
Match a character that is not within the specified range, such as '[^ A-FH-Z] rep' match a letter that does not start with the A-R and T-Z, followed by the rep line.
(..)
Mark matching characters, such as '(love)'. Love is marked as 1.
<
Anchor specifies the start of a word, for example :'
>
Anchor specifies the end of a word. For example, 'grep> 'matches the row containing the word ending with grep.
X
Repeat the characters X and M, for example, '0' matches the rows containing 5 o.
X
Repeat character X, at least m times, for example, 'O' matches rows with at least 5 o.
X
Repeated characters X, at least m times, no more than N times. For example, 'O' matches rows of 5--10 O.
W
Match text and number characters, that is, [A-Za-z0-9], for example, 'gw * P' matches with g followed by zero or multiple characters or numbers, followed by P.
W
Matches one or more non-word characters, such as periods, and periods.
B
The word lock character. For example, 'bgrepb' only matches grep.

3. Meta character extension set for egrep and grep-e
+
Matches one or more previous characters. For example, '[A-Z] + able' matches one or more lower-case letters followed by able strings, such as loveable, enable, and disable.
?
Matches zero or multiple previous characters. For example, 'gr? P' matches gr followed by one or no characters, and then the row of P.
A | B | C
Match A, B, or C. For example, grep | sed matches grep or sed.
()
Group symbols, such as: Love (able | RS) ov + matches loveable or lovers and matches one or more ov.
X, X, X
Same as X, X, X

4. POSIX character class
Is
The POSIX (the Portable Operating System
Interface) added a special character class, such as [: alnum:] is another way of writing the A-Za-z0-9. Put them in the [] to become a regular expression, such as [-
Za-z0-9] or [[: alnum:]. In Linux, grep supports POSIX character classes except fgrep.

[: Alnum:]
Character
[: Alpha:]
Character
[: Digit:]
Numeric characters
[: Graph:]
Non-empty characters (non-space and control characters)
[: Lower:]
Lowercase characters
[: Cntrl:]
Control characters
[: Print:]
Non-empty characters (including spaces)
[: Punct:]
Punctuation Marks
[: Space:]
All blank characters (new line, space, Tab)
[: Upper:]
Uppercase characters
[: Xdigit:]
Hexadecimal number (0-9, A-F, A-F)

5. grep Command Options
-?
At the same time, the upper and lower lines of matching rows are displayed? Line. For example, grep-2 pattern filename simultaneously displays the upper and lower rows of matching rows.
-B, -- byte-offset
Print the block number of the row before the matching row.
-C, -- count
Only the number of matched rows is printed, and the matching content is not displayed.
-F file, -- file = File
Extract templates from files. The empty file contains 0 templates, so nothing matches.
-H, -- no-filename
When multiple files are searched, the matching file name prefix is not displayed.
-I, -- ignore-case
Ignore case differences.
-Q, -- quiet
Cancel display. Only the exit status is returned. 0 indicates that the matched row is found.
-L, -- files-with-matches
Print the list of files matching the template.
-L, -- files-without-match
Print the list of files that do not match the template.
-N, -- line-Number
Print the row number before the matched row.
-S, -- silent
The error message about the nonexistent or unreadable file is not displayed.
-V, -- revert-match
Reverse search: Only unmatched rows are displayed.
-W, -- word-Regexp
If it is referenced, the expression is used as a word search.
-V, -- version
Displays the software version information.

6. Instance
To make good use of the grep tool, we need to write a regular expression. Therefore, we will not explain all the functions of grep here. We will only list a few examples to illustrate how to write a regular expression.

$ LS-L | grep '^'
Filter the LS-L output content in the MPs queue and display only the rows starting with.

$ Grep 'test' D *
Display all the lines containing test in files starting with D.

$ Grep 'test' AA BB CC
The row Matching Test is displayed in the AA, BB, and CC files.

$ Grep '[A-Z] 'aa
Display All rows of a string that contains at least five consecutive lowercase characters.

$ Grep 'W (ES) T. * 'AA

If West is matched, ES is stored in the memory, marked as 1, and any characters (. *). These characters are followed by another ES (). If they are found, the row is displayed. If you use egrep or grep-E, you do not need to escape it by using the "" sign. You can directly write it as 'W (ES) T.

Use 'grep' to search for text files
If you want to find a string in several text files, you can use the 'grep' command. 'Grep' searches for the specified string in the text.
Suppose you are searching for a file with the string 'Magic 'in the'/usr/src/Linux/documentation' directory:

$ Grep magic/usr/src/Linux/documentation /*
Sysrq.txt: * how do I enable the magic sysrq key?
Sysrq.txt: * how do I use the magic sysrq key?

The 'sysrp.txt 'file contains this string. The sysrq function is discussed.

By default, 'grep' only searches for the current directory. If the directory contains many subdirectories, 'grep' is listed as follows:
Grep: Sound: is a directory

This may make the output of 'grep' difficult to read. There are two solutions:

Search for subdirectories: grep-R
Or ignore the subdirectory: grep-D skip
Of course, if you expect a lot of output, you can use the pipeline to transfer it to the 'less'. Read:
$ Grep magic/usr/src/Linux/documentation/* | less

In this way, you can read more conveniently.

Note that you must provide a file filtering method (* for searching all files *). If you forget, 'grep' will wait until the program is interrupted. If this happens, press and try again.

The following are some interesting command line parameters:
Grep-I pattern files: searches case-insensitive. Case Sensitive by default,
Grep-l pattern files: only names of matched files are listed,
Grep-l pattern files: Lists unmatched file names,
Grep-W pattern files: match only the entire word, not a part of the string (for example, match 'Magic ', not 'magical '),
Grep-C number pattern files: the matching context displays the rows of [number,
Grep pattern1 | pattern2 files: displays the rows matching pattern1 or pattern2,
Grep pattern1 files | grep pattern2: displays rows that match both pattern1 and pattern2.
Here are some special symbols used for search:

/Respectively mark the start and end of a word.
For example:
Grep man * matches 'Batman ', 'manic', 'Man ', etc,
Grep '/
Grep '/' only matches 'man ', not other strings such as 'Batman' or 'manic.
'^': Indicates the first row of the matched string,
'$': Indicates the end of a matched string,
If you are not familiar with command line parameters, you can try 'grep' on the GUI, such as rexgrep. This software provides and, or, not, and other syntaxes, as well as beautiful buttons. If you only need more explicit output, try fungrep.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.