Merge pull request #361 from Linux-pdz/master

translated  12 Practical Examples of Linux grep Command
This commit is contained in:
Xingyu.Wang 2013-11-05 23:55:58 -08:00
commit 8e359b543a
2 changed files with 119 additions and 125 deletions

View File

@ -1,125 +0,0 @@
翻译中 by Linux-pdz
12 Practical Examples of Linux grep Command
================================================================================
Have you ever been confronted with the task of looking for a particular string or pattern in a file, yet have no idea where to start looking? Well then, here is **grep** to the rescue!
![](http://www.tecmint.com/wp-content/uploads/2013/11/Grep-Command-Examples.png)
*12 Grep Command Examples*
**grep** is a powerful file pattern searcher that comes equipped on every distribution of **Linux**. If, for whatever reason, it is not installed on your system, you can easily install it via your package manager (**apt-get** on **Debian/Ubuntu** and **yum** on **RHEL/CentOS/Fedora**).
$ sudo apt-get install grep #Debian/Ubuntu
$ sudo yum install grep #RHEL/CentOS/Fedora
I have found that the easiest way to get your feet wet with **grep** is to just dive right in and use some real world examples.
### 1. Search and Find Files ###
Lets say that you have just installed a fresh copy of the new **Ubuntu** on your machine, and that you are going to give **Python** scripting a shot. You have been scouring the web looking for tutorials, but you see that there are two different versions of **Python** in use, and you dont know which one was installed on your system by the **Ubuntu** installer, or if it installed any modules. Simply run this command:
$ sudo dpkg l | grep i python
#### Sample Output ####
ii python2.7 2.7.3-0ubuntu3.4 Interactive high-level object-oriented language (version 2.7)
ii python2.7-minimal 2.7.3-0ubuntu3.4 Minimal subset of the Python language (version 2.7)
ii python-openssl 0.12-1ubuntu2.1 Python wrapper around the OpenSSL library
ii python-pam 0.4.2-12.2ubuntu4 A Python interface to the PAM library
First, we ran **dpkg l**, which lists installed ***.deb** packages on your system. Second, we piped that output to **grep i** python, which simple states “go to grep and filter out and return everything with python in it.” The **i** option is there to ignore-case, as **grep** is case-sensitive. Using the **i** option is a good habit of getting into, unless of course you are trying to nail down a more specific search.
### 2. Search and Filter Files ###
The grep can also be used to search and filter within individual files or multiple files. Lets take this scenario:
You are having some trouble with your **Apache Web Server**, and you have reached out to one of the many awesome forums on the net asking for some help. The kind soul who replies to you has asked you to post the contents of your **/etc/apache2/sites-available/default-ssl** file. Wouldnt it be easier for you, the guy helping you, and everyone reading it, if you could remove all of the commented lines? Well you can! Just run this:
$ sudo grep v “#” /etc/apache2/sites-available/default-ssl
The **v** option tells **grep** to invert its output, meaning that instead of printing matching lines, do the opposite and print all of the lines that dont match the expression, in this case, the **#** commented lines.
### 3. Find all .mp3 Files Only ###
The **grep** can be very useful for filtering from **stdout**. For example, lets say that you have an entire folder full of music files in a bunch of different formats. You want to find all of the ***.mp3** files from the artist **JayZ**, but you dont want any of the remixed tracks. Using a **find command** with a couple of **grep** pipes will do the trick:
$ sudo find . name “*.mp3” | grep i JayZ | grep vi “remix”
In this example, we are using find to print all of the files with a ***.mp3 extension**, piping it to **grep i** to filter out and prints all files with the name “**JayZ**” and then another pipe to **grep vi** which filters out and does not print all filenames with the string (in any case) “**remix**”.
- [35 Practical Examples of Linux Find Command][1]
### 4. Display Number of Lines Before or After Search String ###
Another couple of options are the A and B switches, which displays the matched line and number of lines either that come before or after the search string. While the man page gives a more detailed explanation, I find it easiest to remember the options as A = after, and B = before:
$ sudo ifconfig | grep A 4 eth0
$ sudo ifconfig | grep -B 2 UP
### 5. Prints Number of Lines Around Match ###
The greps **C** option is similar, but instead of printing the lines that come either before or after the string, it prints the lines in either direction:
$ sudo ifconfig | grep C 2 lo
### 6. Count Number of Matches ###
Similar to piping a **grep** string to word count (**wc** program) greps built-in option can perform the same for you:
$ sudo ifconfig | grep c inet6
### 7. Search Files by Given String ###
The **n** option for **grep** is very useful when debugging files during compile errors. It displays the line number in the file of the given search string:
$ sudo grep n “main” setup..py
### 8. Search a string Recursively in all Directories ###
If you would like to search for a string in the current directory along with all of the subdirectories, you can specify the **r** option to search recursively:
$ sudo grep r “function” *
### 9. Searches for the entire pattern ###
Passing the **w** option to grep searches for the entire pattern that is in the string. For example, using:
$ sudo ifconfig | grep w “RUNNING”
Will print out the line containing the pattern in quotes. On the other hand, if you try:
$ sudo ifconfig | grep w “RUN”
Nothing will be returned as we are not searching for a pattern, but an entire word.
### 10. Search a string in Gzipped Files ###
Deserving some mention are greps derivatives. The first is **zgrep**, which, similar to **zcat**, is for use on **gzipped** files. It takes the same options as **grep** and is used in the same way:
$ sudo zgrep i error /var/log/syslog.2.gz
### 11. Match Regular Expression in Files ###
The **egrep** is another derivative that stands for “**Extended Global Regular Expression**”. It recognizes additional expression meta-characters such **at + ?** | and **()**. egrep is very useful for searching source files, and other pieces of code, should the need arise. It can be invoked from regular grep by specifying the **E** option.
$ sudo grep E
### 12. Search a Fixed Pattern String ###
The **fgrep** searches a file or list of files for a fixed pattern string. It is the same as **grep F**. A common way of using **fgrep** is to pass a file of patterns to it:
$ sudo fgrep f file_full_of_patterns.txt file_to_search.txt
This is just a starting point with **grep**, but as you are probably able to see, it is invaluable for a variety of purposes. Aside from the simple one line commands we have implemented, **grep** can be used to write powerful **cron** jobs, and robust **shell scripts**, for a start. Be creative, experiment with the options in the **man page**, and come up with **grep expressions** that serve your own purposes!
--------------------------------------------------------------------------------
via: http://www.tecmint.com/12-practical-examples-of-linux-grep-command/
译者:[译者ID](https://github.com/译者ID) 校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[1]:http://www.tecmint.com/35-practical-examples-of-linux-find-command/

View File

@ -0,0 +1,119 @@
Linux中grep命令的12个实践例子
===
你是否遇到过需要在文件中查找一个特定的字符串或者模式的任务,但是仍然不知道从哪开始?这儿是一些**grep**的例子可以给你帮助。
![](http://www.tecmint.com/wp-content/uploads/2013/11/Grep-Command-Examples.png)
*12个grep命令的例子*
**grep**是每个**Linux**发行版都预装的一个强有力文件匹配搜索工具。无论何种原因,如果你的系统没有预装它的话,你可以很容易的通过你系统的包管理器来安装它(**Debian/Ubuntu**系中的**apt-get**和**RHEl/CentOS/Fedora**系中的**yum**)。
$ sudo apt-get install grep #Debian/Ubuntu
$ sudo yum install grep #RHEL/CentOS/Fedora
我发现使用现实世界中的真实例子让你投身其中是让你接触**grep**命令的最容易方式。
###1.搜索和寻找文件
假设你已经在你的电脑上安装了一个全新的**Ubuntu**,你打算卸载**Python**。你浏览网页寻找教程,但是你发现存在两个不同版本的**Python**在使用,而你不知道你的**Ubuntu**安装器到底在你的系统中安装了哪个版本的Python也不知道它安装了哪些模块。解决这个烦恼只需简单的运行以下命令
$ sudo dpkg -l | grep -i python
####输出例子
ii python2.7 2.7.3-0ubuntu3.4 Interactive high-level object-oriented language (version 2.7)
ii python2.7-minimal 2.7.3-0ubuntu3.4 Minimal subset of the Python language (version 2.7)
ii python-openssl 0.12-1ubuntu2.1 Python wrapper around the OpenSSL library
ii python-pam 0.4.2-12.2ubuntu4 A Python interface to the PAM library
首先,我们运行**dpkg -l**列出你系统上安装的**.deb**包。接着,我们使用管道将输出结果传输给命令**grep -i** python这一步可以简单解释为把结果传输给grep然后过滤出所有含有python的项并返回结果。只要你不打算详细的指定搜索方式那么使用选项**-i**是个好习惯。
###2.搜索和过滤文件
grep还可以在一个或多个文件夹里用于搜索和过滤。让我们来看一个这样的情景
你的**Apache网页服务器**出现了问题,你不得不从许多专业网站找一个发帖询问。好心的回复你的人会让你粘贴你的**/etc/apache2/sites-available/default-ssl**文件。网友帮助了你,而假如你能移除掉所有的注释行,那么今后大家都能阅读到这个解决方案,这对你来说会会困难吗?你当然可以很容易的做到!只需这样做就可以了:
$ sudo grep -v "#" /etc/apache2/sites-available/default-ssl
选项**-v**是告诉**grep**命令反转它的输出结果,意思就是不输出匹配的项,做相反的事,打印出所有不匹配的项。这个例子中,有**#**的是注释行。
###3.找出所有的mp3文件
**grep**命令对于过滤来自于**标准输出**的结果非常有用。例如,假设你的一个文件夹里面全是各种格式的音乐文件。你要找出艺术家**jayZ**的所有**mp3**格式的音乐文件,里面也不要有任何混合音轨。使用**find命令**再结合管道使用**grep**就可以完成这个魔法:
$ sudo find . -name ".mp3" | grep -i JayZ | grep -vi "remix""
在这个例子中我们使用find命令打印出所有以**.mp3**为后缀名的文件,接着将其使用管道传递给**grep -i**过滤和打印出名字为“**JayZ**”的文件,再使用管道传送给**grep -vi**以便过滤掉含有“**remix**”的项。
- [35个Linux中find命令的实践例子][1]
###4.在搜索字符串前面或者后面显示行号
另外两个选项是-A和-B之间的切换是用以显示匹配的行以及行号分别控制在字符串前或字符串后显示。Man页给出了更加详细的解释我发现一个记忆的小窍门-A=after、-B=before。
$ sudo ifconfig | grep -A 4 etho
$ sudo ifconfig | grep -B 2 UP
###5.在匹配字符串周围打印出行号
grep命令的**-C**选项和例4中的很相似不过打印的行号并不是在匹配字符串的前面或后面而是而是按照顺序打印出匹配的行
$ sudo ifconfig | grep -C 2 lo
###6.计算匹配项的数目
这个功能类似于将**grep**输出的结果用管道传送给计数器(**wc**程序grep内建的选项可以达到同样的目的
$ sudo ifconfig | grep -c inet6
###7.通过给定字符串搜索文件
当你在编译出错时需要调试时,**grep**命令的**-n**选项是个非常有用的功能。它能告诉你所搜索的内容在文件的哪一行:
$ sudo grep -n "main" setup.py
###8.在所有目录里递归的搜索
假若你要在当前文件夹里搜索一个东西,而当前文件夹里又有很多子目录,你可以指定一个**-r**选项以便于递归的搜索:
$ sudo grep -r "function" *
###9.进行完全匹配搜索
传递**-w**选项给grep命令可以在字符串中进行完全匹配搜索。例如向下面这样输入
$ sudo ifconfig | grep -w “RUNNING”
将打印出含有引号内匹配项的行。另外,你还可以试一下这个:
$ sudo ifconfig | grep -w “RUN”
搜索这个匹配项时,若搜索的东西里面没有这样的一个单独的单词,将什么也不会返回。
###10.在Gzip压缩文件中搜索
我们还要关注一下grep的衍生应用。第一个是**zgrep**,这个与**zcat**很相似,可以用于在**gzip**压缩过的文件中进行搜索。它有与**grep**相似的命令,使用方式也一样:
$ sudo zgrep -i error /var/log/syslog.2.gz
###11.在文件中匹配正则表达式
**egrep**是另一个衍生应用,代表着“**扩展全局正则表达式**”。它可以识别更多的正则表达式元字符,例如**at + ?** | 和****。在搜索源代码文件时egrep是一个非常有用的工具还有其他的一些零碎代码文件的搜索需要使得这样的搜索能力成为必需。也可以grep命令中指定选项**-E**来获得加强正则表达式搜索的能力。
$ sudo grep -E
###12.搜索一个固定匹配字符串
**fgrep**用以在一个文件或文件列表中搜索固定匹配的字符串。功能与**grep -F**同。**fgrep**的一个通常用法为传递一个含有匹配字符串的文件给它:
$ sudo fgrep -f file_full_of_patterns.txt file_to_search.txt
这仅仅是**grep**命令的开始,但是你可能已经注意到,它对于实现各种各样的目的简直是太有用了。除了这种我们实施的只有一行的命令,**grep**还可以写成**cron**任务或者自动的**shell脚本**去执行。保持好奇心,试验一下**man页**的各个选项,为实现你的目的写出一些**grep表达式**。
---
via: http://www.tecmint.com/12-practical-examples-of-linux-grep-command/
译者:[Linux-pdz](https://github.com/Linux-pdz) 校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[1]:http://www.tecmint.com/35-practical-examples-of-linux-find-command/