grep
(global search regular expression(RE) and print out the line,全面搜索正则表达式并把行打印出来)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来
命令格式:grep 参数 文件1...
-
在多个文件中搜索某个内容
grep "wojiushiwo" test.log test1.log
//在test.log和test1.log中搜索含有wojiushiwo的数据行 -
输出除match_pattern之外的所有行 -v选项
grep -v "wojiushiwo" test.log
-
标记匹配颜色 --color=auto
grep "match_pattern" file_name --color=auto
-
使用正则表达式 -E选项
grep -E "^9" test.log
//搜索以数字9开头的行 -
只输出文件中匹配到的部分 -o选项
grep -o match_pattern file_name
echo this is a test line. | grep -o -E "[a-z]+\."
//输出line. -
统计文件或者文本中包含匹配字符串的行数 -c选项
grep -c "wojiushiwo" test.log
//输出2 表示匹配到两行包含wojiushiwo的数据 -
输出包含匹配字符串的行数 -n选项
grep "wojiushiwo" -n file_name
-
搜索多个文件并查找匹配文本在哪些文件中
grep -l "wojiushiwo" test.log test1.log
//输出test.log 表示匹配文本在test.log文件中 -
递归搜索文件
grep "wojiushiwo" . -r
//在当前目录下 递归搜索文本是"wojiushiwo"的文件 -
显示匹配某个结果之后的3行,使用 -A(after)选项;-B(before)选项,前n行;-C前后n行
grep "wojiushiwo" -A 3 test.log
//查询出符合匹配结果的后3行 -
-i 忽略大小写