grep的三种变形
Grep:标准grep命令
Egrep:扩展grep,支持基本及扩展的正则表达式,但不支/q模式范围的应用
Fgrep:快速grep 允许查找字符串而不是一个模式
grep选项
-c 只输出匹配行的计数
-i 不区分大小写
-h 查询多文件是不显示文件名
-l 查询多文件时只输出包含匹配字符的文件名
-n 显示匹配行及行号
-s 不显示不存在或无匹配文本的错误信息
-v 显示不包含匹配文本的所有行
1.查询多个文件:
如果想要在当前目录下查的所有.txt中查找字符串"am" 下面命令即可
# grep "am" *.txt
hello.txt:I am Tom
在当前目录所有文件中查找字符串"am"
# grep "am" *
hello.txt:I am Tom
myfile2:I am Tom
youfile:I am Tom
2.行匹配
下面命令解释为 在hello.txt文件中 有1行包含字符"am"
# grep -c "am" hello.txt
1
下面显示hello.txt中包含"am"字符串的1行
# grep "am" hello.txt
I am Tom
3.行数
下面命令解释为 在myfile.txt中 显示满足匹配模式的所有行 即包含字符串"am"的行数
前面数字表示在文件中的行号 后面跟匹配字符
# grep -n "am" youfile.txt
2:am box
5:you name
6:i am grep
4.显示非匹配行
下面命令和上面3相反 显示不包含"am"的个行 但不显示所在文件中的行号
# grep -v "am" youfile.txt
Hello
how are you
fine
5.精确匹配
下面命令解释为 精确抽取"am"
# grep "am/>" youfile.txt
am box
i am grep
am
6.大小写敏感
下面命令查询 不管是大写"Am" 还是小写"am" 都匹配 使用-i
# grep -i "am" youfile.txt
am box
you name
i am grep
am
Am
-----------------------------无聊的分割线--------------------------------------
grep和正则表达式
1.模式范围
下面命令使用正则表达式 解释为 匹配2开头 以5或7结尾的字符串
# grep "2[57]" hello.txt
25 age
257 day
27 age
2.不匹配行首
下面命令解释为 抽取记录 使其行首不是2的字符
# grep "^[^2]" hello.txt
33 age
67 day
3.设置大小写
#grep "[Aa]" hello.txt
4.匹配任意字符
下面命令抽取 以 a 开头 m结尾 长度为3的字符
# grep "a.m" hello.txt
asm
5.范围组合
下面命令解释为 第一个字符在0-9之间 第二个字符2-5之间
# grep "[0-9][2-5]" hello.txt
25 age
257 day
33 age
6.空行
使用^和$可查询空行
# grep "^$" hello.txt
使用-n参数显示实际空行数 下面命令解释为 空行在第一行和第四行
# grep -n "^$" hello.txt
1:
4: