Linux grep and regular expression, grep Regular Expression

Source: Internet
Author: User
Tags grep regular expression expression engine egrep

Linux grep and regular expression, grep Regular Expression
Grep Introduction

Grep is a powerful text search tool that uses regular expressions to search for text and print matching rows. Generally, grep has three versions: grep, egrep (equivalent to grep-E), and fgrep. Egrep is the extended grep, and fgrep is the quick grep (fixed string for text search, does not support regular expression reference, but queries are extremely fast ). Grep is one of the three swordsmen for Linux text processing.

Grep usage

Usage: grep [OPTIONS] PATTERN [FILE...]

Grep [OPTIONS] [-e PATTERN |-f FILE] [FILE...]

Common options:

-- Color = auto: color the matched text and highlight it;

-I: Ignore the case sensitivity of characters.

-O: only the matched strings are displayed.

-V: displays rows that cannot be matched by the pattern.

-E: supports the use of extended Regular Expressions

-Q: In silent mode, no information is output.

-A #: display the row matched by the Pattern and Its suffix # Row

-B #: displays the row matched by the Pattern and Its front # The row

-C #: displays the rows matched by the pattern and their front and back # Rows

   Note: When grep is used for matching, double quotation marks must be used (single quotation marks are strongly referenced) to prevent errors caused by incorrect parameters or special commands. Extended grep usage

Usage: egrep [OPTIONS] PATTERN [FILE...]

Grep-E [OPTIONS] PATTERN [FILE...]

-I: Ignore the case sensitivity of characters.
-O: only the matched strings are displayed.
-V: displays the rows that are not matched by the pattern.
-Q: In silent mode, no information is output.
-A #: display the row matched by the Pattern and Its suffix # Row
-B #: displays the row matched by the Pattern and Its front # The row
-C #: displays the rows matched by the pattern and their front and back # Rows
-G: supports basic regular expressions.

Grep Regular Expression metacharacters

'^': Specifies the beginning of the line.

'$': The end of the anchor row.

'.': Match any one character

'*': Matches zero or multiple previous characters.

'\? ': Match the first character 0 or 1 time;

'\ +': Match the first character once or multiple times;

'\ {M \}': match the character m times before it (\ is an escape character)

'\ {M, n \}': match the first character at least m times, at most n times

'[]': Match a character in the specified range | '[^]' matches any single character out of the specified range

'\ <' Or '\ B': the beginning of the anchor, '\>' or '\ B': The end of the anchor (\ <PATTERN \>: match the complete word)

'\ (\)': Process multiple characters as a whole

  Backward reference: refers to the character that matches the pattern in the group brackets.

The content that matches the pattern in the group brackets or is automatically recorded by the Regular Expression Engine in internal variables:

\ 1: The pattern matches from the left, the first left brace, and the matching right brace.

\ 2: The mode starts from the left side, the second left brace, and the matching content between the right brace...

  The extension regular expression is slightly different from the regular expression:

'[]': It still matches any single character in the specified range, but there are many special matching methods.

[: Digit:] match any single number

[: Lower:] match any single lowercase letter

[: Upper:] match any single uppercase letter

[: Alpha:] match any single letter

[: Alnum:] match any single letter or number

[: Punct:] match any single symbol

[: Space:] matches a single space

Escape characters are canceled in some places:

'? ': Match the first character 0 or 1 time;

'+': Match the first character once or multiple times;

'{M}': match the character m times before it (\ is an escape character)

'{M, n}': match the first character at least m times, at most n times

(): Bind one or more characters for processing as a whole, and use reverse references as usual.

'|': Or (Note: 'C | cat' is C and cat, '(C | C) at is cat and cat ')

Exercise questions:

1. List the usernames of all logged-on users on the current system. Note: Only one user is displayed when you log on to the same system multiple times.

[root@localhost ~]# who | cut -d' ' -f1|uniqroot

2. Retrieve Information about the user logging on to the current system.

[root@localhost ~]# id `last | head -1 | cut -d' ' -f1`uid=0(root) gid=0(root) groups=0(root)

3. Retrieve the shell on the current system that the user uses as the largest default shell.

[root@localhost ~]# cut -d':' -f7 /etc/passwd|uniq -c|sort -n|tail -1|cut -d' ' -f7/sbin/nologin

4. Change the information of the last 10 users with the maximum value of the Third Field in/etc/passd to uppercase and save it to the/tmp/maxuser.txt file.

[root@localhost ~]# sort -t':' -k3 -n /etc/passwd|tail -10|tr 'a-z' 'A-Z' >/tmp/maxusers.txt[root@localhost ~]# cat /tmp/maxusers.txt NOBODY:X:99:99:NOBODY:/:/SBIN/NOLOGINSYSTEMD-NETWORK:X:192:192:SYSTEMD NETWORK MANAGEMENT:/:/SBIN/NOLOGINNGINX:X:996:994:NGINX WEB SERVER:/VAR/LIB/NGINX:/SBIN/NOLOGINCHRONY:X:997:995::/VAR/LIB/CHRONY:/SBIN/NOLOGINPOLKITD:X:998:996:USER FOR POLKITD:/:/SBIN/NOLOGINSYSTEMD-BUS-PROXY:X:999:997:SYSTEMD BUS PROXY:/:/SBIN/NOLOGINDINGJIE:X:1000:1000:DINGJIE:/HOME/DINGJIE:/BIN/BASHJEFF:X:1001:1024:WOSHIDASHUAIBI:/HOME/JEFF:/BIN/BASHEGON:X:1002:1002::/HOME/EGON:/BIN/BASHNFSNOBODY:X:65534:65534:ANONYMOUS NFS USER:/VAR/LIB/NFS:/SBIN/NOLOGIN

5. Retrieve the IP address of the current host

[root@localhost ~]# ifconfig | egrep "inet.*broadcast.*"|cut -d' ' -f10192.168.0.133

6. List the names of all files ended with. conf In The/etc directory, convert the names to uppercase, and save them to the/tmp/etc. conf file.

[root@localhost ~]# find /etc -name '*.conf' | egrep -o "[^/]*(\.conf)$"|tr 'a-z' 'A-Z' >/tmp/etc.conf[root@localhost ~]# cat /tmp/etc.conf RESOLV.CONFCA-LEGACY.CONFFASTESTMIRROR.CONFLANGPACKS.CONFSYSTEMD.CONFVERSION-GROUPS.CONFLVM.CONFLVMLOCAL.CONFASOUND.CONFLDAP.CONFMLX4.CONFRDMA.CONFSMTPD.CONF

7. display the total number of sub-directories or files under the/var directory

[root@localhost ~]# ls /var | wc -l21

8. Retrieve the names of the 10 groups with the smallest value in the Third Field of/etc/group.

[root@localhost ~]# sort -t: -k3 -n /etc/group|head -10 |cut -d':' -f1rootbindaemonsysadmttydisklpmemkmem

9. Merge the/etc/fstab and/etc/issue files into the same content and save it to the/tmp/etc. test file.

[root@localhost ~]# cat /etc/fstab /etc/issue > /tmp/etc.test[root@localhost ~]# cat /tmp/etc.test ## /etc/fstab# Created by anaconda on Sat May 13 10:12:58 2017## Accessible filesystems, by reference, are maintained under '/dev/disk'# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info#/dev/mapper/cl-root     /                       xfs     defaults        0 0UUID=2789d01a-4e2b-47a5-9c3c-537641648663 /boot                   xfs     defaults        0 0/dev/mapper/cl-swap     swap                    swap    defaults        0 0\SKernel \r on an \m

The use of regular expressions requires more connections to enhance memory. Otherwise, it is difficult to use regular expressions. During the learning process, remember to write more and back.

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.