Home >Operation and Maintenance >Linux Operation and Maintenance >Introduction to Linux command grep
1. Function
The grep command in Linux system is a powerful text search tool. It can use regular expressions to search for text and print out the matching lines. The full name of grep is Global Regular Expression Print, which means the global regular expression version. Its usage permissions are for all users.
2. Format
grep [options]
3. Main parameters
[options]Main parameters:
-c: Only the count of matching rows is output.
-I: Insensitive to uppercase and lowercase (only applicable to single characters).
-h: Do not display the file name when querying multiple files.
-l: When querying multiple files, only the file names containing matching characters will be output.
-n: Display matching lines and line numbers.
-s: Do not display error messages that do not exist or have no matching text.
-v: Display all lines that do not contain matching text.
pattern Regular expression main parameters:
\: Ignore the original meaning of special characters in the regular expression.
^: matches the starting line of the regular expression.
$: Matches the end line of the regular expression.
\<: Start from the line matching the regular expression.
\>: To the end of the line matching the regular expression.
[ ]: A single character, such as [A], that is, A meets the requirements.
[-]: Range, such as [A-Z], that is, A, B, C to Z all meet the requirements.
. : All single characters.
*: There are characters, and the length can be 0.
4. A simple example using the grep command
$ grep ‘test’ d*
Displays the lines containing test in all files starting with d.
$ grep ‘test’ aa bb cc
Display the lines matching test in the aa, bb, cc files.
$ grep ‘[a-z]\{5\}’ aa
Displays all lines containing strings each of which has at least 5 consecutive lowercase characters.
$ grep 'w\(es\)t.*\1′ aa
If west is matched, es is stored in memory and marked as 1, and then searches for any characters (.*), these characters are followed by another es (\1), and the line is displayed when found. If you use egrep or grep -E, there is no need to escape with the "\" sign, just write it directly as 'w(es)t.*\1'.
5.grep command usage complex example
Suppose you are searching for files with the string 'magic' in the '/usr/src/Linux/Doc' directory:
$ grep magic /usr/src/Linux/Doc/*
sysrq.txt:* How do I enable the magic SysRQ key?
sysrq.txt:* How do I use the magic SysRQ key?
The file 'sysrp.txt' contains this string and discusses the function of SysRQ.
By default, 'grep' only searches the current directory. If there are many subdirectories under this directory, 'grep' will list it like this:
grep: sound: Is a directory
This may make the output of 'grep' difficult to read. There are two solutions here:
Explicitly request to search subdirectories: grep -r
or ignore subdirectories: grep -d skip
If there is a lot of output, You can pipe it to 'less' to read:
$ grep magic /usr/src/Linux/Documentation/* | less
This way you can read it more conveniently .
One thing to note is that you must provide a file filtering method (use * to search all files). If you forget, 'grep' will wait until the program is interrupted. If you encounter this, press
There are some interesting command line parameters below:
grep -i pattern files: Search case-insensitively. The default is case-sensitive,
grep -l pattern files: Only matching file names are listed,
grep -L pattern files: Unmatched file names are listed,
grep -w pattern files: only match the entire word, not part of the string (such as matching 'magic', not 'magical'),
grep -C number pattern files: match the context respectively Display [number] lines,
grep pattern1 | pattern2 files: Display lines matching pattern1 or pattern2,
grep pattern1 files | grep pattern2: Display lines matching both pattern1 and pattern2.
grep -n pattern files can display the line number information
grep -c pattern files can find the total number of lines
There are also some special symbols for searching:
\< and \> mark the beginning and end of words respectively.
For example:
grep man * will match 'Batman', 'manic', 'man', etc.
grep '\ grep '\ '^': means that the matched string is at the beginning of the line, '$': means that the matched string is at the end of the line, Grep command usage list 1. Parameters: -I: Ignore case -c: Print the number of matching lines -l: Find files containing Matches -v: Find lines that do not contain matches -n: Print lines and line labels that contain matches 2, RE (regular expression) \ Ignore the original meaning of special characters in the regular expression ^ Match the beginning line of the regular expression $ Match the end line of the regular expression \< Start with the line matching the regular expression \> To the end of the line that matches the regular expression [ ] Single character; such as [A] means A meets the requirements [ - ] Range; such as [A-Z] means A , B, C to Z all meet the requirements . All single characters * All characters, the length can be 0 3. Example # ps -ef | grep in.telnetd root 19955 181 0 13:43:53 ? 0:00 in.telnetd # more size.txt Contents of size file b124230 b034325 a081016 m7187998 m7282064 a022021 a061048 m9324822 b103303 a013386 b044525 m8987131 B081016 M45678 B103303 BADc2345 # more size.txt | grep '[a-b]' range; such as [A-Z], that is, A, B, C to Z all meet the requirements b124230 b034325 a081016 a022021 a061048 b103303 a013386 b044525 # more size.txt | grep '[a-b]'* b124230 b034325 a081016 m7187998 m7282064 a022021 a061048 m9324822 b103303 a013386 b044525 m8987131 B081016 M45678 B103303 BADc2345 # more size.txt | grep 'b' single character; For example, [A] means A meets the requirements b124230 b034325 b103303 b044525 # more size.txt | grep ' [bB]' b124230 b034325 b103303 b044525 B081016 B103303 BADc2345 # grep 'root' /etc/group root::0:root bin::2:root,bin,daemon sys::3:root,bin,sys,adm adm::4:root,adm,daemon uucp::5:root,uucp mail::6:root tty::7:root,tty,adm lp::8:root,lp,adm nuucp::9:root ,nuucp daemon::12:root,daemon # grep '^root' /etc/group matches the starting line of the regular expression root::0: root # grep 'uucp' /etc/group uucp::5:root,uucp nuucp::9:root,nuucp # grep '\ uucp::5:root,uucp # grep 'root$' /etc/group Match the end line of the regular expression root::0:root mail::6:root # more size.txt | grep -i 'b1..*3' -i : Ignore size Write b124230 b103303 B103303 # more size.txt | grep -iv 'b1..*3' -v: Find does not contain Matching row b034325 a081016 m7187998 m7282064 a022021 a061048 m9324822 a013386 b044525 m8987131 B081016 M45678 BADc2345 # more size.txt | grep -in 'b1..*3' 1:b124230 9:b103303 15:B103303 # grep '$' /etc/init.d/nfs.server | wc -l 128 # grep '\$' /etc/init.d/nfs.server | wc -l Ignore the original meaning of special characters in regular expressions 15 # grep '\$' /etc/init.d/nfs.server case " $1" in >/tmp/sharetab.$$ [ "x$fstype" != xnfs ] && echo "$path\t$res\ t$fstype\t$opts\t$desc" >>/tmp/sharetab.$$ /usr/bin/touch -r /etc/dfs/sharetab / tmp/sharetab.$$ /usr/bin/mv -f /tmp/sharetab.$$ /etc/dfs/sharetab if [ -f /etc/dfs/dfstab ] && /usr/bin/egrep -v '^[ ]*(#|$)' if [ $startnfsd -eq 0 -a -f /etc/rmmount.conf ] && if [ $startnfsd -ne 0 ]; then elif [ ! -n "$_INIT_RUN_LEVEL" ]; then while [ $wtime -gt 0 ]; do wtime=`expr $wtime - 1` if [ $wtime -eq 0 ]; then echo "Usage: $0 { start | stop }" # more size.txt the test file their are files The end # grep 'the' size.txt the test file their are files # grep '\ the test file their are files # grep 'the\>' size.txt the test file # grep '\ the test file # grep '\<[Tt]he\>' size.txt the test file ========== ================================================== ====== 1,Introduction A multi-purpose text search tool using regular expressions. This php?name=%C3%FC%C1%EE" onclick="tagshow(event)" class="t_tag"> command is originally an ed line editor A php?name=%C3%FC%C1%EE" onclick="tagshow(event)" class="t_tag">Command/Filter: g/re/p -- global - regular expression - print. Basic format grep pattern [file...] (1)grep search string [filename] (2)grep regular expression [filename] Search for all occurrences of pattern in the file. Pattern can be either a string to be searched or a regular expression. Note: It is best to use double quotes when entering the string to be searched/and when using regular expressions for pattern matching, pay attention to using single quotes 2, grep option -c Only output the count of matching lines -i is case-insensitive (for single characters) -n displays matching line numbers -v does not display non-containing matches All lines of text -s does not display error messages -E uses extended regular expressions For more options, please see: man grep 3, Commonly used grep examples (1) Multiple file query grep "sort" *.doc #See file name matching (2) Line matching: Output the count of matching lines grep -c "48" data.doc #Output the number of lines containing 48 characters in the document (3) Display matching lines and number of lines grep -n "48" data.doc #Display all lines and line numbers that match 48 (4) Display non-matching lines grep -vn "48" data.doc # Output all lines that do not contain 48 (4) Display non-matching lines grep -vn "48" data.doc #Output all lines that do not contain 48 (5) Case sensitive grep -i "ab" data.doc #Output all lines containing strings of ab or Ab 4, application of regular expressions (1)Application of regular expressions (note: it is best to enclose regular expressions in single quotes) grep '[239].' data.doc #Output all files that contain numbers ending with 2, 3 or Lines starting with 9 and containing two numbers (2) Mismatch test grep '^[^48]' data.doc #Does not match lines whose beginning is 48 (3) Use extended pattern matching grep -E '219|216' data.doc (4) ... This needs to be Continuously apply and summarize in practice, and master regular expressions proficiently. 5, use class name You can use the class name for international pattern matching: [[:upper:]] [A-Z] [[ :lower:]] [a-z] [[:digit:]] [0-9] [[:alnum:]] [0-9a-zA-Z] [[:space:]] Space or tab [[:alpha:]] [a-zA-Z] (1) Use grep '5[[:upper:]][[:upper:]]' data.doc #Query lines starting with 5 and ending with two capital letters The above is the detailed content of Introduction to Linux command grep. For more information, please follow other related articles on the PHP Chinese website!