Detailed explanation of grep commands-9 typical use cases

Source: Internet
Author: User
Tags perl regular expression

Grep
Global Regular Expression print, indicating a Global Regular Expression
Is a powerful text search tool that uses regular expression matching.
1. Command Format
Grep [Options] files


2. Main Parameters
-C: only the number of matched rows is output.
-I: case insensitive
-N: displays the matched flight and line number.
-L: When querying multiple files, only file names containing matching characters are output.
-V: reverse matching, that is, displaying unmatched rows
-H: the file name is not applicable during query.
-S: no error message is displayed.


3. Some Regular Expressions
\ Negative characters: for example, "\" \ "" indicates matching ""
^ $ Start and end
[] Single character, [a]
[-] Match a range. [0-9a-za-z] matches all numbers and letters.
* The first character appears 0 or multiple times
+ The preceding characters appear once or multiple times.
. Any character

4. Typical scenarios

Unless case sensitive, add-I to ignore the case sensitivity.

(1) combined with the find command and pipeline
One of your music folders contains files in multiple formats, and you only want to find the artist Jay's MP3 file without any mixed audio tracks.
[[email protected] ~]#find . -name ".mp3" | grep -i jay | grep -vi "remix"
Analysis: 1) Use Find-name to list all MP3 files and redirect them to grep.
2) use grep-I to find rows containing Jay
3) Use grep-VI to find rows that do not contain remix


(2)-a-B-c
In many cases, we care about matching rows but the context of matching rows. In this case,-a-B-c is useful.
-N rows after a n, and a memory is (after)
-N rows before B n, and B memory is (Before)
-C n: N rows before, N rows after, and C: Center)
Example
[[email protected] ~]# ifconfig | grep -A 2 "Link encap"eth0      Link encap:Ethernet  HWaddr 00:0C:29:F3:38:15            inet addr:192.168.91.129  Bcast:192.168.91.255  Mask:255.255.255.0          inet6 addr: fe80::20c:29ff:fef3:3815/64 Scope:Link--lo        Link encap:Local Loopback            inet addr:127.0.0.1  Mask:255.0.0.0          inet6 addr: ::1/128 Scope:Host[[email protected] ~]#  ifconfig | grep -C 2 "lo"          Interrupt:67 Base address:0x2024 lo        Link encap:Local Loopback            inet addr:127.0.0.1  Mask:255.0.0.0          inet6 addr: ::1/128 Scope:Host


(3) count with-C
You have a large file that contains a website, such as www.baidu.com tieba.baidu.com. How many websites are affiliated with Baidu?
[
[email protected] ~]# grep -c "*baidu.com*" filename例子[[email protected] ~]# cat file.txtwtmp begins Mon Feb 24 14:26:08 2014192.168.0.1162.12.0.123"123"123""123[email protected][email protected] 123www.baidu.comtieba.baidu.comwww.google.comwww.baidu.com/search/index[[email protected] ~]# grep -cn ".*baidu.com.*" file.txt 3

(4)-r recursive search for subdirectories
Find the files that contain matching characters under the extremely subdirectory of the current directory
Find the subdirectory and output the row number after matching. The vertex here indicates the current directory.

[[Email protected] ~] # Grep-Nr hello_hwc_csnd_blog *.

Example:

[[email protected] ~]# grep -nr baidu ../file.txt:8:www.baidu.com./file.txt:9:tieba.baidu.com./file.txt:11:www.baidu.com/search/index./test/test.txt:1:http://www.baidu.com

Search for subdirectories. After matching, only the file name is output.
[[Email protected] ~] # Grep-LR hello_hwc_csnd_blog *.

Example:

[[email protected] ~]# grep -lr baidu ../file.txt./test/test.txt


(5) -- line-buffered open buffering Mode
A file is dynamic. It constantly adds information to the end of the file, and you want to output rows containing some information. That is, a continuous grep dynamic stream


[[Email protected] ~] # Tail-F file | grep -- line-buffered your_pattern


(6) Search processes with PS
[[email protected] ~]# ps aux | grep initroot         1  0.0  0.1   2072   632 ?        Ss   22:52   0:01 init [5]                             root      4210  0.0  0.1   6508   620 ?        Ss   23:01   0:00 /usr/bin/ssh-agent /bin/sh -c exec -l /bin/bash -c "/usr/bin/dbus-launch --exit-with-session /etc/X11/xinit/Xclients"root      4233  0.0  0.0   2780   504 ?        S    23:01   0:00 /usr/bin/dbus-launch --exit-with-session /etc/X11/xinit/Xclientsroot      4956  0.0  0.1   3920   680 pts/1    R+   23:27   0:00 grep init

Here we see grep init. The commands we run are also listed.
If you don't want this line, we can change the command like this.
[[email protected] ~]# ps aux | grep [i]nitroot         1  0.0  0.1   2072   632 ?        Ss   22:52   0:01 init [5]                             root      4210  0.0  0.1   6508   620 ?        Ss   23:01   0:00 /usr/bin/ssh-agent /bin/sh -c exec -l /bin/bash -c "/usr/bin/dbus-launch --exit-with-session /etc/X11/xinit/Xclients"root      4233  0.0  0.0   2780   504 ?        S    23:01   0:00 /usr/bin/dbus-launch --exit-with-session /etc/X11/xinit/Xclients

(7) Search for a directory that does not contain
[[Email protected] ~] # Grep-r -- exclude-Dir = node_modules 'some pattern'/path/to/search

Example

[[email protected] ~]# lsanaconda-ks.cfg  Desktop  file.txt  find.result  install.log  install.log.syslog  test[[email protected] ~]# grep -r baidu ../file.txt:www.baidu.com./file.txt:tieba.baidu.com./file.txt:www.baidu.com/search/index./test/test.txt:http://www.baidu.com
If we do not want to include the test directory

[[email protected] ~]# grep -R --exclude-dir=text "baidu" ../file.txt:www.baidu.com./file.txt:tieba.baidu.com./file.txt:www.baidu.com/search/index
If an error is reported

grep: unrecognized option `--exclude-dir=test'

If the version is too old, update it.


(8) Search for IP addresses
Here the-O and-P commands are used.
We can use man grep to view
-O, -- only-matching:
Show only the part of a matching line that matches pattern.
-P, -- Perl-Regexp:
Interpret pattern as a Perl regular expression.
That is to say,-o only displays the part that matches the regular expression in the matching row.
-P, used as Perl Regular Expression matching
[[email protected] ~]# cat file.txtwtmp begins Mon Feb 24 14:26:08 2014192.168.0.1162.12.0.123"123"123""123[email protected][email protected] 123www.baidu.comtieba.baidu.comwww.google.comwww.baidu.com/search/index[[email protected] ~]# grep -oP "([0-9]{1,3}\.){3}[0-9]{1,3}" file.txt192.168.0.1162.12.0.123

(9) Find the mailbox

[[Email protected] ~] # Grep-op "[a-zA-Z0-9 _-] + @ [a-zA-Z0-9 _-] + (\. [a-zA-Z0-9 _-] +) +" file.txt

Example

[[email protected] ~]# cat file.txtwtmp begins Mon Feb 24 14:26:08 2014192.168.0.1162.12.0.123"123"123""123[email protected][email protected] 123www.baidu.comtieba.baidu.comwww.google.comwww.baidu.com/search/index[[email protected] ~]# grep -oP "[a-zA-Z0-9_-][email protected][a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+" file.txt[email protected][email protected]



Detailed explanation of grep commands-9 typical use cases

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.