强大的grep
语法
# grep match_pattern filename //将会输出符合match_pattern规定的内容,match pattern为通配符
# grep -E match_pattern filename //这里的match_pattern为正则表达式
# grep -o -E match_pattern filename //只输出匹配的部分
# grep -v match_pattern filename //包含math_pattern匹配的行之外的行
# grep -c "text" filename //匹配字符串的行数
# egrep -o match_pattern | wc -l //字符串出现的次数
# grep "text" . -R -n //递归搜索文件
# grep -e match_pattern -e match_pattern //匹配多个样式
# grep -f pattern_file source_filename //匹配多个样式,样式以文件的形式出现
# grep match_pattern -A 3 //某个结果之后的3行
# grep match_pattern -B 3 //某个结果之前的3行
# grep match_pattern -C 3 //某个结果的前后3行
应用
搜索文件中字符串"linux"出现的行
# grep linux -n sample.txt
1:gnu is not linux
2:linux is fun
搜索多个文件字符串"linux"出现的行
# grep linux -n sample.txt sample2.txt
sample.txt:1:gnu is not linux
sample.txt:2:linux is fun
sample2.txt:4:planetlinux
使用正则表达式搜索字符串"is"
# egrep "[i|s]+ " sample.txt
gnu is not linux
linux is fun
bash is art
计算匹配字符串not在整个文件中出现的位置
# egrep "[i|s]+ " -b -o sample.txt
4:is
23:is
35:is
搜索多个文件并找出匹配文本位于哪一个文件中
# grep -l linux sample.txt sample2.txt
sample.txt
sample2.txt
搜索不包含匹配文本的文件
# grep -L linux sample.txt sample2.txt
递归搜索文件
# grep "linux" . -R -n
./sample2.txt:4:planetlinux
./data.txt:4:4 linux 1000
./newDir/sample.txt:1:gnu is not linux
./newDir/sample.txt:2:linux is fun
./sample.txt:1:gnu is not linux
./sample.txt:2:linux is fun
搜索文件时忽略大小写
# grep -i "LINUX" sample.txt
gnu is not linux
linux is fun
匹配多个样式
# grep -e "gun" -e "linux" sample.txt
gnu is not linux
linux is fun
搜索中包括或排除文件
# grep "hello" . -r --include *.txt
out.txt:hello
# grep "hello" . -r --exclude "*.txt"
./test:hello
使用文件作为匹配样式
sh-4.1# cat seed.txt bow sh-4.1# cat foo.txt bow bowel bow 123 sh-4.1# grep -f seed.txt foo.txt bow bowel bow 123 sh-4.1# grep -wf seed.txt foo.txt //选择包含整个匹配项的行 bow bow 123 sh-4.1# grep -xf seed.txt foo.txt //选择完全匹配的行 bow
文件是否包含指定的文本
#!/bin/bash if [ $# -ne 2 ]; then echo "$0 match_text filename" fi match_text=$1 filename=$2 grep -q $match_text $filename if [ $? -eq 0 ]; then echo "the text exsit" else echo "text doesn't exsit" fi
# ./silent_grep.sh student stu_data.txt
the text exsit
浙公网安备 33010602011771号