打印出包含某字符的所以字符串(区分大小写)
- grep hello testfile.txt
加-i可以忽略大小写
- grep -i hello testfile.txt
加-w可以精确匹配
- grep -w hello testfile.txt
加-e可以实现多个条件查找
- grep -e hello -e today testfile1.txt
加-n可以显示行数
- grep -n hello testfile1.txt
加-r递归查找所有含有此字符的文件
- grep -r hello testdir/
加-l仅仅查找文件名
- grep -lr hello testdir/
加-E启用正则表达式
- grep -E 'hello|today' testfile1.txt
正则表达式常用速查表
元字符/表达式 | 功能说明 | grep -E 示例 | 匹配效果 |
|---|---|---|---|
. | 匹配任意单个字符(除换行符) | grep -E "a.c" test.txt | 匹配 abc、a1c、a#c 等(a和c之间任意1个字符) |
[] | 匹配括号内任意单个字符,可写范围 | grep -E "[0-9a-z]" test.txt | 匹配任意1个数字或小写字母 |
[^] | 匹配括号外任意单个字符(取反) | grep -E "[^a-z]" test.txt | 匹配非小写字母的字符(数字、大写、符号等) |
* | 匹配前导字符 0 个或多个 | grep -E "ab*" test.txt | 匹配 a、ab、abb、abbb 等(b可出现0次及以上) |
+ | 匹配前导字符 1 个或多个(核心常用) | grep -E "a+" test.txt | 匹配 a、aa、aaa 等(a至少出现1次,不匹配空) |
? | 匹配前导字符 0 个或 1 个(可选匹配) | grep -E "a?" test.txt | 匹配空、a(a最多出现1次) |
{n} | 精确匹配前导字符 n 次 | grep -E "a{2}" test.txt | 仅匹配 aa(a恰好出现2次) |
{n,} | 匹配前导字符至少 n 次 | grep -E "a{2,}" test.txt | 匹配 aa、aaa、aaaa 等(a至少出现2次) |
{n,m} | 匹配前导字符 n 到 m 次(含边界) | grep -E "a{2,4}" test.txt | 匹配 aa、aaa、aaaa(a出现2-4次) |
^ | 匹配行首(行的开头位置) | grep -E "^start" test.txt | 匹配以 start 开头的行 |
$ | 匹配行尾(行的结束位置) | grep -E "end$" test.txt | 匹配以 end 结尾的行 |
| | 逻辑“或”,匹配多个表达式中的任意一个(核心常用) | grep -E "error|warn" test.log | 匹配含 error 或 warn 的行 |
() | 分组匹配,将多个字符视为一个整体(核心常用) | grep -E "(ab)+" test.txt | 匹配 ab、abab、ababab 等(ab作为整体重复) |
\< | 匹配词首(单词的开头位置) | grep -E "\<hello" test.txt | 匹配 hello、helloworld 等(以 hello 开头的单词) |
\> | 匹配词尾(单词的结束位置) | grep -E "hello\>" test.txt | 匹配 hello、worldhello 等(以 hello 结尾的单词) |