日期:2014-05-16  浏览次数:20724 次

Linux grep命令用法

首先创建我们练习grep命令时需要用到的demo文件demo_file。

$ cat demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
This Line Has All Its First Character Of The Word With Upper Case.

Two lines above this line is empty.
And this is the last line.

1.从单个文件中搜索指定的字串

grep的基础用法是如下例的从指定的文件中搜索特定的字串。

语法:
grep "literal_string" filename

$ grep "this" demo_file
this line is the 1st lower case line in this file.
Two lines above this line is empty.
And this is the last line.

2. 在多个文件中检索指定的字串

语法:
grep "string" FILE_PATTERN


先拷贝demo_file为demo_file1。grep的结果在符合条件的行前将包括文件名。当文件名包含元字符时,linux shell会将匹配的所有文件作为输入到grep中去。

$ cp demo_file demo_file1

$ grep "this" demo_*
demo_file:this line is the 1st lower case line in this file.
demo_file:Two lines above this line is empty.
demo_file:And this is the last line.
demo_file1:this line is the 1st lower case line in this file.
demo_file1:Two lines above this line is empty.
demo_file1:And this is the last line.

3. 用 grep -i 进行大小写无关的搜索

语法:
grep -i "string" FILE


也是一个基本用法,对搜索的字串忽略大小写,因此下例中匹配“the”, “THE” and “The”。

$ grep -i "the" demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
This Line Has All Its First Character Of The Word With Upper Case.
And this is the last line.

4. 使用用正则表达式

语法:
grep "REGEX" filename


如果你能有效地利用正则表达式,这是个很有用的特点。在下面的例子中,搜索全部以“lines”开始以“empty”结束的字串,如搜索“lines[之间任意字]empty” ,并且忽略大小写。

$ grep -i "lines.*empty" demo_file
Two lines above this line is empty.