1.基本使用
grep:查找哪个文件中有字符串A,并将A对应文件和A所在行打印出来。
如:
# 查找满足条件的文件
grep include *cpp # 查找以cpp结尾的文件中有哪些文件是包含字符串include,以及打印include所在行
输出如下:
test2.cpp:#include<iostream>
test.cpp:#include<iostream>
# 查找目录下所有文件
grep -r include ./ # 查找当前目录下所有包含字符串include的文件以及打印include所在行
输出如下:
./test.i:# "/usr/include/c++/9/iostream"
./test.i:# "/usr/include/c++/9/iostream"
# 查找不包含某字符的文件及其对应行
grep -v include *cpp* # 查找文件名包含cpp的文件中不包含include的行
输出如下:
test2.cpp:int main(){
test2.cpp: std::cout << "/*";
test2.cpp: std::cout << "*/";
test2.cpp: // std: :cout << /* "*/" */;
test2.cpp: // std: :cout << /* "*/" /* "/*" */;
test2.cpp: return 0;
test2.cpp:}
test.cpp:int main(){
test.cpp: std::cout << "/*";
test.cpp: std::cout << "*/";
test.cpp: // std: :cout << /* "*/" */;
test.cpp: // std: :cout << /* "*/" /* "/*" */;
test.cpp: return 0;
test.cpp:}
# 总结:
$ grep "被查找的字符串" 文件名 # 从文件内容查找匹配指定字符串的行
$ grep –r "被查找的字符串" 目录名 # 查找目录下所有文件有哪些文件的哪些行满足条件
$ grep –e "正则表达式" 文件名 # 从文件内容查找与正则表达式匹配的行
$ grep –i "被查找的字符串" 文件名 # 查找时不区分大小写
$ grep -c "被查找的字符串" 文件名 # 查找匹配的行数
$ grep –v "被查找的字符串" 文件名 从文件内容查找不匹配指定字符串的行
2. |的使用
某查询命令|grep “被查找的字符串”:中间的|功能是把上一条命令的输出,作为下一条命令的参数,如:
ps -ef |grep java
其中ps -ef输出所有进程的状态
grep java代表在ps -ef输出的文本中查找java这个字段
如果连续使用 | grep xxx ,就相当于 一层层的过滤筛选。 比如 ps -ef | grep java |grep jenkins |grep httpPort
再如:
ls ./ | grep bash
查找ls输出的信息中是否含有带字符串bash
3.其他
sudo grep -r -i pypi.douban.com / # 从根目录开始找含有pypi.douban.com的文件
参考:https://blog.csdn.net/auccy/article/details/79376680