Linux Grep 命令指南 (grep command cheatsheet)

By Long Luo

USAGE WILDCARDS Match any Character Except New Line Match 0 or One characters DESCRIPTION Match 0 or More characters Match 1 or More characters $ grep ‘alias’ filname {n} {n,} Matches n or More {,m} Matches up to m (maximum) -c -e -f POSITIONS Match 0 or One characters Match 0 or More characters BRE, ERE & PCRE (Global / Regular Expression search / and Print) Perl Compatible Regular Expressions (PCRE) Additional anchors and character classes, lookahead/lookbehind, conditional expressions, comments, and other features are available in PCRE. Extended Regular Expressions (ERE) Unless they are escaped with a backslash, ERE gives each of these characters a unique meaning: Match any Character Except New Line [OPTION…] PATTERNS [FILE…] $ grep [OPTION…] -e PATTERNS … [FILE…] S grep [OPTION…] -f PATTERN_FILE … [FILE…] grep searches each FILE for PATTERNS. PATTERNS is a string that contains one or more patterns separated by newline characters, and grep prints each line that matches a pattern. When using grep in a shell command, PATTERNS should usually be quoted. A FILE of” ” denotes standard input. If no FILE is specified, recursive searches examine the working directory, while nonrecursive searches read standard input. Furthermore, the variant programs egrep, fgrep, and rgrep are equivalent to grep -E, grep -F, and grep -r, respectively. These variants are obsolete, but remain available for backward compatibility.

OPTIONS EXAMPLES -v -m -n -n -o -x -w -A -B -C -E grep -c ‘error’ /var/log/syslog grep -e ‘linux$’ filename grep -f patternjile .bashrc grep -i ‘Alias’ .bashrc grep -I ‘alias’ /home/traw/ grep -L ‘alias’ /home/traw/ grep -r ‘error’ /var/log/log.txt grep -v ‘warning’ /home/traw/log.txt grep -m 3 ‘alias’ .bashrc grep -n ‘sudo’ .bashrc grep -n ‘sudo’ .bashrc grep -o ‘search string’ .bashrc grep -x ‘linux is love’ filename grep -w “alias” .bashrc grep -A 6 ‘error” error.log grep -B 2 ’warning’ error.log grep -C 7 ‘info’ error.log grep -E ‘b(a|e)g’ filename QUANTIFIERS {n,m} CHARACTER CLASSES [A-Za-z] [0-9] Matches exactly n times find all occurrences of a string (basic usage). count the number of matches. use regex (lines ending with ‘Linux’). take PATTERNS from FILE. ignore case search. returns files with matches. returns files without matches. recursive search (within subdirs). select non-matching lines. limit grep Output upto 3 lines. print line numbers of the matches. print line numbers of the matches. only show the matching part of the string. match only whole lines match only whole words print 6 lines after a match print 2 lines before a match print 7 lines before and after a match Extended regex (lines containing bag or beg)

WILDCARDS

. Match any Character Except New Line ? Match 0 or One characters * DESCRIPTION Match 0 or More characters + Match 1 or More characters

参考文献

  1. grep