在文件中进行搜索是文本处理的一项重要的工作。
(1)搜索包含特定模式的文本行:
grep pattern filename
or $ grep "pattern" filename
(2) 也可以像下面这样从stdin中读取:
$ echo -e "this is a word\nnext line" | grep word
this is a word
(3)单个grep命令也可以对多个文件进行搜索:
$ grep "match_text:" file1 file2 file3...
(4) 用--color选项可以在输出行中着重标记处匹配的单词:
$ grep word filename --color=auto
this is the line containing word
(5)grep 命令只解释match_text中的某些特殊字符。如果使用正则表达式,需要添加-E选项——这意味着使用扩展正则表达式。或者也可以使用默认允许正则表达式的grep命令——egrep。例如:
$ grep -E "[a-z]+" filename
or $egrep"[a-z]+" filename
(6)只输出文件中匹配到的文体部分,可以使用选项-o:
$echo this is a line .| egrep -o "[a-z]+\."
line.
(7) 要打印出包含match行之外的所有项,可以使用:
$ grep -c "text” filename
10
(8)统计文件或文本中包含匹配字符串的行数:
$grep -c "text" filename
10