A detailed explanation of the Linux grep command usage

Source: Internet
Author: User
Tags character classes grep regular expression posix egrep

Introduction to 1.grep grep (global search Regular expression (RE) and print out of the line, full search of regular expressions and printing of lines) is a powerful text search tool that uses regular expressions to search for text. and print out the matching lines. The grep family of Unix includes grep, Egrep, and Fgrep. Egrep and Fgrep commands are only a small difference from grep. Egrep is the extension of grep, which supports more re metacharacters, and fgrep is fixed grep or fast grep, which regards all the letters as words, that is, the metacharacters in the regular expression represents the literal meaning back to itself, no longer special. Linux uses the GNU version of grep. It is more powerful and can use the Egrep and FGREP functions with the-G,-e,-f command line options. grep works in such a way that it searches for a string template in one or more files. If the template includes spaces, it must be referenced, and all strings after the template are treated as filenames. The results of the search are sent to the screen without affecting the contents of the original file. grep can be used for Shell scripting, because grep describes the status of the search by returning a status value, or 0 if the template search succeeds, or 1 if the search is unsuccessful, or 2 if the searched file does not exist. We can use these return values to do some automated text processing work. Function Description: Find the string that matches the condition in the file. Syntax: grep [-abcefghhillnqrsvvwxy][-a][-b][-c] [-d][-e][-f][--help][template style] [file or directory ...] Supplemental Note: The grep directive is used to find the file containing the specified template style, and if the contents of a file are found to conform to the specified template style, the preset grep directive will display the column containing the template style. If no file name is specified, or if the given file name is "-", the grep instruction reads the data from the standard input device. Parameter:-A or--text do not ignore binary data. -A or--after-context= in addition to displaying the column that conforms to the template style, and displays the contents after that column. -B or--byte-offset indicates the bit number of the first character of the column before displaying the column that conforms to the template style. -B or--before-context= in addition to displaying the column that conforms to the template style, and displays the contents before the column. -C or--count calculates the number of columns that conform to the template style. -C or--context= or--in addition to displaying the column that conforms to the template style, and displays the contents before the column. -D or--directories= You must use this parameter when you specify that you want to find a directory rather than a file, otherwise the GREP directive returns information and stops the action. -E or--regexp= specifies the string as the template style for finding the contents of the file. -E or--extended-regexp uses the template style as an extended normal notation. -F or--file= specifies a template file with the contents of one or more template styles that let grep find the contents of the file that match the template criteria, in the form of a template style for each column. -F or--fixed-regexp treats the template style as a list of fixed strings. -G or--basic-regexp use the template style as normal notation. -H or--no-filename does not indicate the file name that the column belongs to until it displays the column that conforms to the template style. -H or--with-filename indicates the file name that the column belongs to before it displays the column that conforms to the template style. -I or--ignore-case ignores the difference in the case of characters. -L or--file-with-matches lists file names that match the file contents to the specified template style. -L or--files-without-match lists file names that do not conform to the specified template style. -N or--line-number indicates the column number of 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 the effect of this parameter is the same as specifying the "-D recurse" parameter. -S or--no-messages does not display an error message. -V or--revert-match reverse lookup. -V or--version displays version information. -W or--WORD-REGEXP displays only the columns that match the whole word. -X or--LINE-REGEXP displays only columns that are eligible for all columns. -Y the effect of this parameter is the same as specifying the "-i" parameter. --help online Help. 2. grep regular expression meta character set (base set) ^ The beginning of the anchor line is as follows: ' ^grep ' matches all rows that begin with grep. The end of the anchor line is as follows: ' grep$ ' matches all rows ending with grep. Match a non-newline character such as: ' GR.P ' matches gr followed by an arbitrary character followed by P. * Match 0 or more previous characters such as: ' *grep ' matches all of one or more spaces followed by the grep line. * Together with any character represented. [] matches a specified range of characters, such as ' [Gg]rep ' matches grep and grep. [^] matches a character that is not within the specified range, such as: ' [^a-fh-z]rep ' matches does not contain a-r andThe t-z begins with a letter that follows the rep line. (..) Mark matching characters, like ' (Love) ', and Love is labeled as 1. < anchor the beginning of the word, such as: ' > Anchor the end of the word, such as ' grep> ' matches the line containing the word that ends with grep. X repeats the characters x,m times, such as: ' 0 ' matches rows containing 5 O. X repeats the character X, at least m times, such as: ' O ' matches at least 5 rows of O. X repeats the character X, at least m times, not more than n times, such as: ' O ' matches the line of 5--10 O. W matches literal and numeric characters, that is, [a-za-z0-9], such as: ' Gw*p ' matches 0 or more literal or numeric characters with g followed by P. The reverse form of WW, matching one or more non-word characters, such as the dot period. The B-word lock, such as: ' BGREPB ' only matches grep. 3. Meta-character expansion set for Egrep and GREP-E + matches one or more previous characters. such as: ' [a-z]+able ', match one or more lowercase letters followed by able strings, such as loveable,enable,disable, etc... match 0 or more previous characters. such as: ' Gr?p ' matches the GR followed by one or no characters, then the line of P. A|b|c matches A or B or C. such as: grep|sed matching grep or sed () grouping symbols, such as: Love (able|rs) ov+ match loveable or lovers, match one or more ov. x,x,x function with x,x,x4. POSIX character classes in order to maintain the character encoding in different countries, POSIX (the portable Operating System Interface) adds special character classes, such as [: Alnum:] is another notation for a-za-z0-9. You can place them in the [] number to be a regular expression, such as [a-za-z0-9] or [[: Alnum:]]. grep under Linux supports POSIX character classes in addition to Fgrep. [: Alnum:] literal numeric character [: Alpha:] literal character [:d igit:] Numeric character [: graph:] non-null character (non-space, control character) [: Lower:] lowercase character [: cntrl:] control character [:p Rint:] non-null character (including spaces) [ :p UNCT:] punctuation [: space:] All whitespace characters (new lines, spaces, tabs) [: Upper:] Uppercase characters [: xdigit:] Hex Number (0-9,A-F,A-F) 5. grep command option-? display matching lines up and down at the same time? Line, such as: grep-2 pattern filename Displays the top and bottom 2 rows of a matching row. -b,--bYte-offset Prints the block number where the line is printed before the matching line. -C,--Count prints only the number of rows that match and does not display matching content. -F File,--file=file extracts the template from the file. An empty file contains 0 templates, so nothing matches. -h,--no-filename the matching file name prefix is not displayed when searching multiple files. -i,--ignore-case ignores case differences. -q,--quiet Suppress and return only the exit status. 0 indicates that a matching row was found. -l,--files-with-matches prints a list of files that match the template. -l,--files-without-match prints a list of files that do not match the template. -n,--line-number prints the line number in front of the matching line. -s,--silent does not display error messages about non-existent or unreadable files. -v,--revert-match, displays only rows that do not match. -w,--word-regexp if referenced, the expression is searched as a single word. -v,--version displays software version information. 6. Example to use grep this tool, in fact, is to write good regular expression, so here does not have all the functions of grep to explain, only a few examples, explain a regular expression of the wording. $ ls-l | grep ' ^a ' filters the contents of the Ls-l output through a pipeline, displaying only the lines that begin with a. The $ grep ' test ' d* shows all the lines in the file that begin with D that contain test. The $ grep ' test ' AA bb cc Displays the line in the aa,bb,cc file that matches the test. $ Grep ' [A-z] ' AA displays all lines containing a string of at least 5 consecutive lowercase characters per string. $ grep ' W (es) t.* ' AA if West is matched, then es is stored in memory, labeled 1, and then searched for any character (. *) followed by another ES (), which is found to display the row. If you use Egrep or GREP-E, do not use the "" number to escape, directly written as ' W (es) t.* ' on it. Search for text files with ' grep ' if you want to find a string in several text files, you can use the ' grep ' command. ' grep ' searches the text for the specified string. 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 MagicSysRq key?sysrq.txt:* How does I use the Magic SysRq key? Where the file ' Sysrp.txt ' contains the string and discusses the functionality of SYSRQ. By default, ' grep ' searches only the current directory. If there are many subdirectories under this directory, ' grep ' is listed in the following form: Grep:sound:Is A directory This may make the output of ' grep ' difficult to read. There are two ways to do this: explicitly require search subdirectories: Grep-r or Ignore subdirectories: grep-d Skip of course, if you anticipate a lot of output, you can go through the pipeline and take it to ' less ' to read: $ grep magic/usr/src/linux/ documentation/* | Less so, you can read more easily. One thing to note is that you need to provide a way to filter the file (search for all files in *). If you forget, ' grep ' will wait until the program is interrupted. If you encounter such a situation, press and then try again. Here are some interesting command-line arguments: grep-i pattern Files: Search by case-insensitive. The default case is case-sensitive, grep-l. Files: Lists only the matching file names, grep-l the pattern files: Lists the mismatched file names, grep-w the pattern: matches only the entire word, not part of the string (such as Match ' Magic ', not ' magical '), grep-c number pattern files: matching contexts display [number] lines, grep pattern1 | PATTERN2 files: Displays rows matching Pattern1 or pattern2, grep pattern1 Files | grep pattern2: Displays rows that match both PATTERN1 and pattern2. Here are some special symbols for searching: \ Mark the beginning and the end of the word, respectively. For example: grep man * will match ' Batman ', ' manic ', ' man ' and so on, grep ' grep ' \ ' matches only ' man ', not ' Batman ' or ' manic ' and other strings. ' ^ ': refers to a matching string at the beginning of the line, ' $ ': refers to the string of matching strings at the end, if you are not accustomed to the command lines parameters, you can try the graphical interface of ' grep ', such as Rexgrep. This software provides syntax for and, or, not, andNice button. If you just need a clearer output, try Fungrep. ------------------------the common command syntax for grep 1. Double quotation marks and single quote references when you enter string parameters in the grep command, it is best to enclose them in double quotation marks. For example: "MyString". There are two reasons to do this, one is to avoid being misunderstood as a shell command, and two is to find a string of multiple words, for example: "Jet Plane", if it is not enclosed in double quotation marks, then the word plane will be mistaken for a file, the query results will return "file does not exist" error message. When calling a variable, you should also use double quotes, such as grep "$ MYVAR" file name, if not, there will be no result returned. Single quotes should be used when calling pattern matching. [[email protected]]# Echo ' grep 123 111.txt ' (#注意是反单引号) 2. The common grep options are:-C outputs only the count of matching rows. -I is case-insensitive (only for single-character). -H does not display a file name when querying multiple files. -L Only output file names that contain matching characters when querying multiple files. -N Displays matching lines and line numbers. -S does not display error messages that do not exist or have no matching text. -V Displays all lines that do not contain matching text. 3. Special – Query in multiple files $ grep "Sort" *.doc (#在当前目录下所有. d o C file to find the string "s O r T") $ grep "Sort It" * (#或在所有文件中查询单词 "Sort It" All of the following examples refer to querying 4 in a single file. Row matches $ grep-c "48″data.f$ 4 (#grep返回数字4, meaning there are 4 lines that contain the string" 4 8″. ) $ grep "48″DATA.F (#显示包含" 4 8″ string of 4 lines of text) 5. Displays the number of rows that satisfy the matching pattern: [[email protected] oid2000]# grep-n 1234 111.txt1:12343:1234ab6. Exact match [[email protected] oid2000]# grep "1234\>" 111.txt12347. Queries for empty rows, querying for rows that begin or end with a condition. Use a combination of ^ and $ to query for blank lines. Use the-n parameter to display the actual number of rows [[EMAil protected] oid2000]# grep-n "^$" 111.txt (return result 2: #说明第二行是空行) [[email protected] oid2000]# grep-n "^abc "111.txt (#查询以abc开头的行) [[email protected] oid2000]# grep-n" abc$ "111.txt (#查询以abc结尾的行) 8. Matches special characters, and queries for characters that have special meanings, such as $. ' "* [] ^ | \ + ? , you must add \ before a specific character. [[email protected] oid2000]# grep "\." 111.txt (#在111. txt in the query contains "." [[email protected] oid2000]# grep "my\.conf" 111.txt (#查询有文件名my. c o n F lines) 9.  directory query [[[email protected] oid2000]# ls-l |grep "^d" (#如果要查询目录列表中的目录) [[email protected] oid2000]# ls-l |grep "^d[d]" (#在一个目录中查询不包含目录的所有文件) [[email protected]]# ls-l |grpe ^d.....x]. X "(#查询其他用户和用户组成员有可执行权限的目录集合)------------------------can be summed up simply as follows: grep command is a line filter tool under Linux, its parameters are numerous, the following describes the role of each parameter, We hope to help you. grep-Print lines matching a pattern (lists the line that conforms to the style) syntax: grep [Options]pattern [FILE ...] grep is used to correspond to a portion of the file in the text, or when no file is specified, the standard input is compared. In a preset scenario, grep lists the line that matches the style. In addition, there are two programs that are grep-type, egrep and Fgrep. Where Egrep is equivalent to GREP-E, Fgrep is equivalent to grep-f. Parameter 1. -A Num,--after-coNtext=num is listed in addition to the line, and the following NUM lines are listed. Example: $ grep-a 1 Panda file (searches for a line with a panda style from file and displays the row's 1 rows) 2. -A or--textgrep is originally a search text file, if the binary file as the target of the search, it will display the following message: Binary file binary file name matches and then end. If you add the-a parameter, you can treat the binary file as a text file search, which is equivalent to the--binary-files=text parameter. Example: (Search for panda style from binary archive mv) (Error!!!) $ grep panda mvbinary file mv matches (this means that the file has a match, see--binary-files=type) $ (correct!!!) $ grep-a Panda mv3. -B Num,--before-context=num is relative to-a num, but this parameter is a num line that displays in addition to the line that matches and appears before it. Example: (search for a line with a panda style from file and display the first 1 lines of that row) $ grep-b 1 panda file4. -C [NUM],-num,--context[=num] lists rows outside the line and lists the upper and lower NUM rows, the default value is 2. Example: (list file In addition to the line containing the panda style and out its top and bottom 2 lines) (to change the default value, change NUM directly) $ grep-c[num] Panda file5. -B,--byte-offset the total number of bytes in the text before the style is listed: Exemple: $ grep-b Panda file Displays the result similar to: 0:panda66:pandahuang123:panda036. --binary-files=type This parameter type is preset to binary (binary), and if it is searched in the normal way, there are only 2 kinds of results: 1. If there is a match: Displays binary file binary file name Matches2. If there is no match: nothing is shown. If type is Without-match, this parameter is encountered, and grep will assume that the binary file does not contain any search styles, the same as the-I parameter. If Tpye is text, grep treats the binary as a text file, the same as the-a parameter. Warning:--binary-files=text If the output is a terminal, it may produce some unnecessaryto the output. 7.-C,--count does not display matching style rows, only shows the total number of rows that are compliant. If you add-V,--invert-match, the parameter shows the total number of rows that are not met. 8.-D action,--directories=action if the file entered is a folder, use the action to process the folder. The default action is read, which means that the folder will be treated as a generic file; If the action is skip (skip), the folder will be skipped by grep: If the action is recurse (recursive), grep will read all the files under the folder, which is equivalent to the-R Parameters. 9.-E, the--EXTENDED-REGEXP uses a regular representation to interpret the style. .-E pattern,--regexp=pattern the style as a partern, usually used to avoid partern use-start. One.-f file,--file=file the style to be searched in advance to a file, a line of style, and then use the file search. An empty file indicates no style to search for, so there will be no match. Example: (NewFile is a search style file) $grep-F newfile file12. -G,--basic-regexp the style as a basic rule-representation interpretation. (This is preset) 13. -H,--with-filename the matching file name before each conforming line, and displays the path if there is a path. Example: (Search for Panda styles in file and testfile) $grep-H panda file./testfilefile:panda./testfile:panda14. -H,--no-filename is similar to the-h parameter, but does not show the path at output. --help generates a short help message. -igrep will force that this binary file does not contain any search styles, as in the--binary-files=without-match parameter. Example: $ grep-i panda mv17. -I,--ignore-case ignores case, contains the style to be searched and the file to be searched. Example: $ grep-i panda mv18. -L,--files-without-match does not display the usual output results, but instead shows the names of the files that are not compliant. .-L,--files-with-matches does not display the usual output results, only the matching file name is displayed. --mmap. If possible, useThe mmap system call goes to read the input instead of the preset read system call. In some situations,--mmap can produce better performance. However,--mmap can cause undefined behavior (including core dump) if the file is shortened in operation, or I/O errors occur. .-N,--line-number the uplink number before the line is displayed. Example: $ grep-n Panda file displays results similar to the following: line number: Matches the contents of the row 22. -Q,--quiet,--silent does not show any general output. See-S or--no-messages23. -r-r,--recursive reads all the files under each folder recursively, which is equivalent to the-D recsuse parameter. .-S,--no-messages does not display error messages that do not exist or cannot be read. Small bet: Unlike GNU grep, traditional grep does not conform to the POSIX.2 protocol because it lacks the-Q parameter, and his-s parameter behaves like the-Q parameter of GNU grep. Shell script tends to migrate traditional grep, bypassing the-Q and-s parameters, and limiting the output to/dev/null. POSIX: Defines the features that UNIX and unix-like systems need to provide. -V,--version displays the version number of grep to the standard error. When you return the bugs about grep, the grep version number must be included. .-V,--invert-match displays all but the search style line. .-W,--word-regexp the search style as a word to search, the line that exactly matches that "word" will be listed. .-X,--line-regexp the search style as a row to search, the lines that exactly match the "line" are listed.


A detailed explanation of the Linux grep command usage

Related Article

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.