通配符
^a 表示匹配以a开头的行
a$表示匹配以$结尾的行
^$表示匹配空行
. 表示任意一个且只有一个字符 不能匹配空行
* 表示匹配前一个字符0次或一次
.* 表示匹配任意字符
a^.* 表示匹配以a开头的任意多个内容
.*$ a 表示匹配以a结尾的任意多个内容
[abc] 表示匹配包含a或b或c的行
[^abc]表示匹配不包含a或b或c的行
扩展的正则表达式
要使用-E才能调用
a+ 表示匹配a字符一次或多次
a? 表示匹配a字符0次或多次
a{n, m} 表示匹配a至少n次最多m次
a{n, } 表示匹配a至少n次 aaaa
a{n} 表示匹配a恰好n次
grep的使用
操作:
-i 表示忽略字符的大小写
-n 表示选择行号
-v 表示排除匹配结果
-c 表示只统计行数
-E 使用扩展正则
-o 表示输出匹配的内容
格式
grep " " file option
grep -E ” “ file option
1:#include <iostream>
2:#include "add.h"
3:using namespace std;
4:class Test:public Sotest{
5:public:
6: void test2(){
7: cout<<"虚函数"<<endl;
8: }
9:
10:};
11:int main(){
12: int a = 10;
13: int b = 20;
14: cout<<"hello world"<<endl;
15: cout<<add(a, b)<<endl;
16: Test s1;
17: s1.test();
18: s1.test2();
19: return 0;
20:
21:}
文件命名为1.cpp
wuze@wuze-virtual-machine:~/c++_project/01/001/src$ grep "^i" 1.cpp -n -i # 匹配以i开头的字符 不论大小写且显示行号
11:int main(){
wuze@wuze-virtual-machine:~/c++_project/01/001/src$ grep "." 1.cpp -n # 结果显示 所有字符 但是不包含空行
wuze@wuze-virtual-machine:~/c++_project/01/001/src$ grep ".*" 1.cpp -n # 包含空行的所有字符
wuze@wuze-virtual-machine:~/c++_project/01/001/src$ grep "^.*i" 1.cpp -n
1:#include <iostream>
2:#include "add.h"
3:using namespace std;
4:class Test:public Sotest{
5:public:
6: void test2(){
11:int main(){
12: int a = 10;
13: int b = 20; # 匹配以任意字符开头到i结束的字符
wuze@wuze-virtual-machine:~/c++_project/01/001/src$ grep [int] 1.cpp -n
1:#include <iostream>
2:#include "add.h"
3:using namespace std;
4:class Test:public Sotest{
5:public:
6: void test2(){
7: cout<<"虚函数"<<endl;
11:int main(){
12: int a = 10;
13: int b = 20;
14: cout<<"hello world"<<endl;
15: cout<<add(a, b)<<endl;
16: Test s1;
17: s1.test();
18: s1.test2();
19: return 0;
# 匹配i或n或t或
wuze@wuze-virtual-machine:~/c++_project/01/001/src$ grep "d.*$" 1.cpp -n
1:#include <iostream>
2:#include "add.h"
3:using namespace std;
6: void test2(){
7: cout<<"虚函数"<<endl;
14: cout<<"hello world"<<endl;
15: cout<<add(a, b)<<endl;
# d开头到任意字符结束的
uze@wuze-virtual-machine:~/c++_project/01/001/src$ grep -E "i+" 1.cpp -n
1:#include <iostream>
2:#include "add.h"
3:using namespace std;
4:class Test:public Sotest{
5:public:
6: void test2(){
11:int main(){
12: int a = 10;
13: int b = 20;
# 匹配至少一个i行
wuze@wuze-virtual-machine:~/c++_project/01/001/src$ grep -E "s{2}" 1.cpp -n
4:class Test:public Sotest{
# 匹配至少连续两个s的行
wuze@wuze-virtual-machine:~/c++_project/01/001/src$ grep -E "a{1,2}" 1.cpp -n -v
5:public:
6: void test2(){
7: cout<<"虚函数"<<endl;
8: }
9:
10:};
13: int b = 20;
14: cout<<"hello world"<<endl;
16: Test s1;
17: s1.test();
18: s1.test2();
19: return 0;
20:
21:}
# 至少1个 最多2 两个连续的字符a