grep(global search regular expression(RE) and print out the line,全面搜索正则表达式并把行打印出来)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。
grep match_pattern file_name
grep "match_pattern" file_name
grep "match_pattern" file1 file2 ...
grep -v "match_pattern" file_name
grep "match_pattern" file_name --color=auto
grep -E "[1-9]+"
或
egrep "[1-9]+"
[root@entel2 test]# echo this is a test line. | grep -o -E "[a-z]+\."
line.
[root@entel2 test]# echo this is a test line. | egrep -o "[a-z]+\."
line.
[root@entel2 test]# cat args.txt
aaa
bbb
ccc
bbb
ddd
aaaaa
[root@entel2 test]# grep -c "aaa" args.txt
2
[root@entel2 test]# grep -n "aaa" args.txt
1:aaa
6:aaaaa
[root@entel2 test]# cat args.txt |grep -n "aaa"
1:aaa
6:aaaaa
#多个文件
grep "match pattern" -n file_1 file_2
[root@entel2 test]# echo gun is not unix | grep -b -o "not"
7:not
[root@entel2 test]#
[root@entel2 test]# echo gun is not unix | grep -b -o "is"
4:is
[root@entel2 test]# echo gun is not unix | grep -b -o "gun"
0:gun
[root@entel2 test]# echo gun is not unix | grep -b -o "i"
4:i
13:i
一行中字符串的字符便宜是从该行的第一个字符开始计算,起始值为0。 选项 -b -o 一般总是配合使用。
[root@entel2 test]# cat grep1.txt
xiaogongjiang
xiaogongjiang1
[root@entel2 test]# cat grep2.txt
xiaogongjiang
this is just for test grep -l
[root@entel2 test]# grep -l "xiaogongjiang" grep1.txt grep2.txt
grep1.txt
grep2.txt
[root@entel2 test]# grep -l "xiaogongjiang" grep*
grep1.txt
grep2.txt
[root@entel2 test]# grep -l "test" grep*
grep2.txt
[root@entel2 test]#
在多级目录中对文本进行递归搜索
# .表示当前目录。
[root@entel2 ~]# grep "xiaogongjiang" . -n -r
./test/grep1.txt:1:xiaogongjiang
./test/grep1.txt:2:xiaogongjiang1
./test/grep2.txt:1:xiaogongjiang
[root@entel2 ~]# echo "hello world" | grep -i "HELLO"
hello world
[root@entel2 ~]# echo this is a text line | grep -e "is" -e "line" -o
is
is
line