grep 是linux中搜索文本时常用的命令,合理使用将极大提高效率
- 命令格式
grep pattern filename1 filename2 ...
# OR
grep "pattern" filename1 filename2 ...
# OR
stdin | grep pattern #stdin为标准输出
- 常用参数
grep word filename --color=auto # 重点标记,相当于--color=always
grep word filename --color=none # 不突出搜索到的内容 相当于 --color=never
grep -E pattern # 使用正则表达式来搜索,或者可以直接使用支持正则表达式的 egrep
grep -o pattern # 只输出匹配到的内容
grep -v pattern # 打印除包含pattern行之外的所有行
grep -c pattern # 统计文件或文本中包含匹配字符串的 》行数
grep -n pattern # 打印包含pattern的行数
grep -b pattern # 打印pattern所在的字节偏移,即索引, 总和 -o 配合使用
grep -l pattern # 搜索多个文件并找出匹配文本位于哪一个文件中
grep -L pattern # 搜索多个文件并返回不匹配的文件列表, 与 -l 相反
# Additionally
grep pattern directory -R # 实现递归查找 和 -r 作用一致
grep -i pattern # 可以忽略大小写
grep -e pattern -e pattern # 可以匹配多个样式
grep -f pattern_file # 从pattern_file中读取出来作为自己的pattern
# 另外可以使用 --include 和 --exclude 排除某些文件
# 可以使用 --exclude-dir 排除某些目录
# 可以使用 --exclude-from FILE 从文件中读取所需要排除的文件列表
eg:
$ grep usage file --color=none
This is a test file. Welcome to learnthe usage of grep - one of linux commands
$ grep -oE "\bc.*s" file
commands $ grep -o 'test' file
test
$ grep -on 'test' file
1:test
$ grep -ob 'test' file
10:test
$ cat file2
This is another test file. This file is used to explain how to use the option -l and so on.
$ grep explain file file2
file2:This is another test file. This file is used to explain how to use the option -l and so on.