syntax
grep [OPTIONS] PATTERN [FILE…]
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE…]- -A get the above line with match lines
- -B get the below line with match lines
- -c count the lines
- -E regular expression
- -i ignore case
- –include=”*.c” only search c files
- -l file with matches
- -L file without matches
- -n line number
- -r recursive
- -w match whole word
- -v invert match
regular expression
- [1-4] match digits from 1 to 4
- [^1-4] exclude 1 to 4
- abc|123 contain abc or 123
POSIX:
- [:alpha:] Any alphabetical character, regardless of case
- [:digit:] Any numerical character
- [:alnum:] Any alphabetical or numerical character
- [:blank:] Space or tab characters
- [:xdigit:] Hexadecimal characters; any number or A–F or a–f
- [:punct:] Any punctuation symbol
- [:print:] Any printable character (not control characters)
- [:space:] Any whitespace character
- [:graph:] Exclude whitespace characters
- [:upper:] Any uppercase letter
- [:lower:] Any lowercase letter
- [:cntrl:] Control characters
skills
count the selected lines, we can do as:
dmesg |grep -i error |wc -l, or like
thisdmesg |grep -i error -csearch by match whole word
dmesg |grep -w 'error'grep -rl --include="*.c" MSG_QUEUE ./select only the lines containing six, seven or eight several times.
grep -E "(six|seven|eight).*\1" test.txtsearch contain TAB key, using [CTRL+V][TAB]
grep " 504 " test.txtgrep -r "abc" /root/sourcegrep -r --include "*.h" "date" pathgrep -m 1 "model name" /proc/cpuinfoonly display the first match linegrep -i -E "abc|123"match abc or 123, -i ignore, -E extended regular expression.grep -r -l "main" .search all files under each directory, -l files-with-match, -L files-withou-matchgrep -w "linux" *.mdmatch wordgrep -rl --include=*.{h,cpp} "socket" .search socket only with .h .cpp filesgrep --exclude-dir="_posts" --exclude-dir="_site" -r "Dennis" ./exclude specify directory