2021-07-29
grep(Global search Regular Expression and Print out the line)
"Global search" 表示全局搜索
"Regular Expression" 表示正则表达式
所以, grep 是一个可以利用 "正则表达式" 进行 "全局搜索" 的工具, grep 会在文本文件中按照指定的正则进行全局搜索,并将搜索出的行打印出来。
不使用正则表达式时也可以使用 grep ,只是当 grep 与正则表达式结合在一起时功能更强大。
# 测试文件 vi test.txt
man‘s youth is a wonderful thing: it is so full of anguish and of magic and he never comes to know it as it is,until it has gone from him forever. It is the thing he cannot bear to lose, it is the thing whose passing he watches with infinite sorrow and regret, it is the thing whose loss with a sad and secret joy, the thing he would never willingly relive again,could it be restored to him by any magic.
1. 简单的字符串查询
# 查询包含 magic 的句子 grep magic test.txt # 使用 -n 选项,显示所属的行 grep -n magic test.txt # 使用 -w 选项,查询完整的单词 grep -nw is test.txt # 使用 -i 选项,忽略大小写 grep -n -i it test.txt # 使用 -c 选项,统计该单词出现的行数 grep -c it test.txt # 使用 -ci 选项,统计该单词忽略大小写情况下出现的行数 grep -ci it test.txt
2. 结合正则表达式
# 查询包含 magic 或 thing 的句子 grep -E "magic|thing" test.txt # 查询包含 i 以及后免的任意字符 grep -E ‘i.*‘ test.txt
# 使用 -v 选项,排除选择的字符 # 查询没有 it 的行,并显示行号 grep -vn ‘it‘ test.txt
# 使用 -A[num] , num可以是一个数字,查询选中句子的后 num 行 grep -A1 "It is the thing he cannot bear to lose," test.txt # 使用 -B[num] , num可以是一个数字,查询选中句子的前 num 行 grep -B1 "It is the thing he cannot bear to lose," test.txt # 使用 -C[num] , num可以是一个数字,查询选中句子的上下 num 行 grep -C1 "It is the thing he cannot bear to lose," test.txt grep -C2 "It is the thing he cannot bear to lose," test.txt