搜索包含特定模式的文本行:
grep "pattern" filename
也可以像下面从stdin中读取:
echo -e "This is a word. \n next line ." |grep word
单个grep命令也可以对多个文件进行搜索:
grep "match_text" file1 file2 file3 ...
用--color选项可以在输出行中着重标记匹配到的单词:
grep word filename --color=auto
grep 命令只解释match_text中的某些特殊字符串。如果需要是用正则表达式,需要添加-E选项,或者使用egrep 。
grep -E "[a-z]+" filename
或
egrep "[a-z]+" filename
只输出文件中匹配到的文本内容,可以使用选项-o:
echo "This is a line ." | egrep -o "[a-z]+."
要打印除包含match_pattern行之外的所有行,可使用:
grep -v match_pattern file
统计文件或文本中包含匹配字符串的行数:
grep -c "text" filename
echo -e "1 2 3 4\nhello\n5 6" |egrep -c "[0-9]"
要文件中拥挤匹配项的数量,可以使用如下的技巧:
echo -e "1 2 3 4 \nhello\n5 6"|egrep -o "[0-9]" |wc -l
打印出包含匹配字符串的行号:
cat sample1.txt
gun is not unix
linux is fun
bash is art
cat sample2.txt
planetlinux
grep linux -n sample1.txt sample2.txt
打印模式匹配所位于的字符或字节偏移:
echo gun is not unix | grep -b -o "not"
搜索多个文件并找出匹配文本位于哪一个文件中:
grep -l linux sample1.txt sample2.txt
忽略样式中大小写
echo Hello world |grep -i "hello"
在grep搜索中指定或排除文件
目录中递归搜索所有的.c和.cpp文件
grep "main()" . -r --include *.{c,cpp}
在搜索中排除所有README文件:
grep "main()" . -r --exclude "README"
如果需要排除目录,可以使用--exclude-dir 选项。
如果需要从文件中读取所需排除的文件列表,使用--exclude-from FILE
使用0值字节作为后缀
echo 'text' > file1
echo 'cool' > file2
echo 'text' > file3
grep "text" file* -lZ |xargs -0 rm打印匹配某个结果之后的前3行,使用-A选项:
seq 10 |grep 5 -A 3
打印匹配某个结果之后的后3行,使用-B选项:
seq 10 |grep 5 -B 3
打印匹配某个结果之后的后3行,使用-C选项:
seq 10 |grep 5 -C 3
用grep在文件中搜索文本
原创
©著作权归作者所有:来自51CTO博客作者mastters的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:正则表达式
下一篇:使用sed进行文本替换
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
findstr KMP grep 在文件中搜索字符串
【代码】findstr KMP grep 在文件中搜索字符串。
c++ c语言 开发语言 #include #endif