码迷,mamicode.com
首页 > 其他好文 > 详细

强大的grep

时间:2015-06-07 13:49:49      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:

语法

# 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

文件是否包含指定的文本

#!/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

 

强大的grep

标签:

原文地址:http://www.cnblogs.com/KarenWang/p/4555406.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!