【Linux相識相知】文本處理工具之grep\egrep\fgrep及Regex,egrepfgrep

來源:互聯網
上載者:User

【Linux相識相知】文本處理工具之grep\egrep\fgrep及Regex,egrepfgrep

常說Linux上有文本處理的三劍客,grep、sed和awk,本文就grep做出詳細的描述,並引出Regex。

 

grep
NAME:列印模式比對的行SYNOPISIS:       grep [OPTIONS] PATTERN [FILE...]       grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]常用選項:--color=auto:對匹配到的文本著色後進行高亮顯示,預設已被別名alias grep='grep --color=auto'-i:忽略字元的大小寫-o:僅顯示匹配到的字串本身-v:顯示不能被模式比對到的行-E:支援使用擴充的Regex-q:靜默模式,即不輸出任何資訊-A #:顯示被模式比對的行及其後#行-B #:顯示被模式比對的行及其前#行-C #:顯示被模式比對的行及其前後各#行

 

舉例1:匹配/etc/passwd下有frank的行

[root@localhost tmp]# grep "frank" /etc/passwdfrank:x:1000:1000:frank:/home/frank:/bin/bash

 

舉例2:匹配/etc/passwd下有frank的行,忽略大小寫

[root@localhost tmp]# grep -i "frank" /etc/passwdfrank:x:1000:1000:frank:/home/frank:/bin/bashFrank:x:1001:1001::/home/Frank:/bin/bash

 

舉例3:匹配/etc/passwd下不能被bash匹配的行

[root@localhost tmp]# grep -v "bash" /etc/passwdbin:x:1:1:bin:/bin:/sbin/nologindaemon:x:2:2:daemon:/sbin:/sbin/nologinadm:x:3:4:adm:/var/adm:/sbin/nologinlp:x:4:7:lp:/var/spool/lpd:/sbin/nologinsync:x:5:0:sync:/sbin:/bin/syncshutdown:x:6:0:shutdown:/sbin:/sbin/shutdown......pulse:x:171:171:PulseAudio System Daemon:/var/run/pulse:/sbin/nologingdm:x:42:42::/var/lib/gdm:/sbin/nologinsshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologinpostfix:x:89:89::/var/spool/postfix:/sbin/nologintcpdump:x:72:72::/:/sbin/nologin

 

舉例4:僅僅匹配/etc/passwd下的frank,忽略大小寫

[root@localhost tmp]# grep -oi "frank" /etc/passwdfrankfrankfrankFrankFrank

 

舉例5:靜默模式比對含有frank的行

[root@localhost tmp]# grep -q "frank" /etc/passwd[root@localhost tmp]# 

 

舉例6:匹配/etc/passwd下含有ftp的行及其後3行

[root@localhost tmp]# grep -A 3 "ftp" /etc/passwdftp:x:14:50:FTP User:/var/ftp:/sbin/nologinnobody:x:99:99:Nobody:/:/sbin/nologinsystemd-bus-proxy:x:999:998:systemd Bus Proxy:/:/sbin/nologinsystemd-network:x:192:192:systemd Network Management:/:/sbin/nologin

 

舉例7:匹配/etc/passwd下含有ftp的行及其前3行

[root@localhost tmp]# grep -B 3 "ftp" /etc/passwdmail:x:8:12:mail:/var/spool/mail:/sbin/nologinoperator:x:11:0:operator:/root:/sbin/nologingames:x:12:100:games:/usr/games:/sbin/nologinftp:x:14:50:FTP User:/var/ftp:/sbin/nologin

 

舉例8:匹配/etc/passwd下含有ftp的行及其前後各2行

[root@localhost tmp]# grep -C 2 "ftp" /etc/passwdoperator:x:11:0:operator:/root:/sbin/nologingames:x:12:100:games:/usr/games:/sbin/nologinftp:x:14:50:FTP User:/var/ftp:/sbin/nologinnobody:x:99:99:Nobody:/:/sbin/nologinsystemd-bus-proxy:x:999:998:systemd Bus Proxy:/:/sbin/nologin

 

egrep

支援擴充Regex實作類別似於grep的文本過濾功能,相當於grep -E

NAME:列印模式比對的行SYNOPISIS:        egrep [OPTIONS] PATTERN [FILE...]   -i:忽略字元的大小寫-o:僅顯示匹配到的字串本身-v:顯示不能被模式比對到的行-q:靜默模式,即不輸出任何資訊-A #:顯示被模式比對的行及其後#行-B #:顯示被模式比對的行及其前#行-C #:顯示被模式比對的行及其前後各#行-G:支援基本Regex

 

fgrep

fgrep搜尋字串而不是搜尋匹配的運算式的模式,所以支援Regex,當無需要用到元字元去編寫入模式的時候,使用fgrep必能更好更快。

支援-i,-v,-o,-A,-B,-C,-p等選項

 

Regex

Regular Expression,Regex,由一類特殊字元及文本字元編寫的模式,其中有些不表示其字面的意義,而是使用者控制或通配功能,分為基本Regex和擴充Regex。

基本Regex元字元:

字元匹配

. :匹配任意單個字元;[]:匹配指定範圍內的任意單個字元;      特殊匹配:[:digit:] 匹配任意單個數字                        [:lower:] 匹配任意單個小寫字母                        [:upper:] 匹配任意單個大寫字母                        [:alpha:] 匹配任意單個字母                        [:alnum:] 匹配任意單個字母或數字                        [:punct:] 匹配任意單個符號                        [:space:] 匹配單個空格[^]:匹配指定範圍外的任意單個字元;

 

匹配次數

用在要指定其出現的次數的字元後面,用於限制其前面字元出現的次數,預設工作於貪婪模式

*:匹配其前面的字元任意次數:0,1,多次      .*:匹配任意長度的任一字元\?:匹配其前面的字元0次或者1次;\+:匹配其前面的字元1次或者多次;\{m\}:匹配其前面的字元m次\{m,n\}:匹配其前面的字元至少m次,至多n次        \{m,\}:至少m次

 

位置錨定

^:托字元,行首錨定,用於模式的最左側$:行尾錨定,用於模式的最右側

單詞:非特殊字元組成的連續字元(字串)都稱為單詞

\<或\b:詞首錨定,用於單詞模式的左側\>或\b:詞尾錨定,使用者單詞模式的右側\<PATTERN\>:匹配完整單詞

 

分組及引用

分組:\(\):將一個或多個字元捆綁在一起,當做一個整體進行處理後向引用:引用前面的分組括弧中的模式所匹配到的字元分組括弧中的模式比對到的內容或被Regex引擎自動記錄於內部的變數中:\1:模式從左側起,第一個左括弧及與之匹配的右括弧之間模式比對到的內容\2:模式從左側起,第二個左括弧及與之匹配的右括弧之間模式比對到的內容以此類推

 

舉例:

1.顯示/etc/passwd檔案中不以/bin/bash結尾的行

[root@localhost tmp]# grep -v "/bin/bash$" /etc/passwdbin:x:1:1:bin:/bin:/sbin/nologindaemon:x:2:2:daemon:/sbin:/sbin/nologinadm:x:3:4:adm:/var/adm:/sbin/nologin......gdm:x:42:42::/var/lib/gdm:/sbin/nologinsshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologinpostfix:x:89:89::/var/spool/postfix:/sbin/nologintcpdump:x:72:72::/:/sbin/nologin

2.找出/etc/passwd檔案中的兩位或三位元字

[root@localhost tmp]# grep "\<[[:digit:]]\{2,3\}\>" /etc/passwdmail:x:8:12:mail:/var/spool/mail:/sbin/nologinoperator:x:11:0:operator:/root:/sbin/nologingames:x:12:100:games:/usr/games:/sbin/nologin......sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologinpostfix:x:89:89::/var/spool/postfix:/sbin/nologintcpdump:x:72:72::/:/sbin/nologin

3.找出etc/grub2.cfg檔案中,以至少一個空白字元開頭,且後面非空白字元的行;

[root@localhost tmp]# grep "^[[:space:]]\+[^[:space:]]" /etc/grub2.cfg   load_env   set default="${next_entry}"   set next_entry=   save_env next_entry   set boot_once=true   set default="${saved_entry}"  menuentry_id_option="--id"  menuentry_id_option=""  set saved_entry="${prev_saved_entry}"  save_env saved_entry  set prev_saved_entry=  save_env prev_saved_entry  set boot_once=true

4.找出"netstat -tan"命令的結果中以LISTEN後跟0,1或多個空白結尾的行

[root@localhost tmp]# netstat -tan | grep  "LISTEN[[:space:]]*$"tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN     tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN     tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN     tcp6       0      0 :::111                  :::*                    LISTEN     tcp6       0      0 :::22                   :::*                    LISTEN     tcp6       0      0 ::1:631                 :::*                    LISTEN     tcp6       0      0 ::1:25                  :::*                    LISTEN 

 

擴充Regex元字元:

字元匹配

. :匹配任意單個字元;[]:匹配指定範圍內的任意單個字元;      特殊匹配:[:digit:] 匹配任意單個數字               [:lower:] 匹配任意單個小寫字母               [:upper:] 匹配任意單個大寫字母               [:alpha:] 匹配任意單個字母               [:alnum:] 匹配任意單個字母或數字               [:punct:] 匹配任意單個符號               [:space:] 匹配單個空格[^]:匹配指定範圍外的任意單個字元;

 

匹配次數

用在要指定其出現的次數的字元後面,用於限制其前面字元出現的次數,預設工作於貪婪模式。

*:匹配其前面的字元任意次數:0,1,多次   .*:匹配任意長度的任一字元?:匹配其前面的字元0次或者1次;+:匹配其前面的字元1次或者多次;{m}:匹配其前面的字元m次{m,n}:匹配其前面的字元至少m次,至多n次   {m,}:至少m次

 

位置錨定

^:托字元,行首錨定,用於模式的最左側$:行尾錨定,用於模式的最右側

單詞:非特殊字元組成的連續字元(字串)都稱為單詞

\<或\b:詞首錨定,用於單詞模式的左側\>或\b:詞尾錨定,使用者單詞模式的右側\<PATTERN\>:匹配完整單詞

 

分組及引用

分組:():將一個或多個字元捆綁在一起,當做一個整體進行處理後向引用:引用前面的分組括弧中的模式所匹配到的字元分組括弧中的模式比對到的內容或被Regex引擎自動記錄於內部的變數中:\1:模式從左側起,第一個左括弧及與之匹配的右括弧之間模式比對到的內容\2:模式從左側起,第二個左括弧及與之匹配的右括弧之間模式比對到的內容以此類推

 

a|b:a或bC|cat:C或cat
(C|c)at:cat或Cat

 

小練習

1、列出當前系統上所有已經登入的使用者的使用者名稱,注意:同一個使用者登入多次,則只顯示一次

who | grep -o "^\<[[:alpha:]]*" | uniqView Code

2、取出最後登入到當前系統的使用者的相關資訊

id `who | tail -1 | grep -o "^\<[[:alpha:]]*"`View Code

3.取出當前系統上被使用者當做其預設shell的最多的那個shell

cut -d: -f7 /etc/passwd | uniq -c | sort -n | tail -1 | cut -d' ' -f7View Code

4.將/etc/passd中的第三個欄位設定最大的後10個使用者的資訊全部給為大寫儲存至/tmp/maxuser.txt檔案中

[root@localhost ~]# sort -t: -k3 -n /etc/passwd | tail -10 | tr 'a-z' 'A-Z' &> /tmp/maxuser.txtView Code

5.取出當前主機的IP地址

ifconfig | grep -Eo "([1-9]|[1-9][1-9]|1[0-9][0-9]|2[0-5][0-4])\.([0-9]|[1-9][1-9]|1[0-9][0-9]|2[0-5][0-5])\.([0-9]|[1-9][1-9]|1[0-9][0-9]|2[0-5][0-5])\.([1-9]|[1-9][1-9]|1[0-9][0-9]|2[0-5][0-4])[[:space:]]" |grep -v "127.0.0.1"或者ifconfig | grep "[[:space:]*]\<inet\>" | cut -d' ' -f10 | grep -v "127.0.0.1"View Code

6.列出/etc目錄下所有已.conf結尾的檔案的檔案名稱,並將其名字轉換為大寫後儲存至/tmp/etc.conf檔案中

find /etc -name "*.conf" | egrep -o "[^/][^/]*$" | tr 'a-z' 'A-Z' > /tmp/etc.testView Code

7.顯示/var目錄下一級子目錄或檔案的總數

ls /etc/ | wc -lView Code

8.取出/etc/group第三個欄位數值最小的10個組的名字

sort -t: -k3 -n /etc/group | head -10 | cut -d: -f1View Code

9.將/etc/fstab和/etc/issue檔案的內容合并為同一個內容後儲存至/tmp/etc.test檔案中

cat /etc/issue /etc/fstab | tee /tmp/etc.test &> /dev/nullView Code

10.顯示/proc/meminfo檔案中以大寫或者小寫S開頭的行,用兩種方式

[root@localhost home]# egrep "^[sS]" /proc/meminfo[root@localhost home]# egrep -i "^s" /proc/meminfo View Code

11.顯示/etc/passwd檔案中其預設shell為非/sbin/nologin的使用者

[root@localhost home]# grep -v "/sbin/nologin" /etc/passwdView Code

12.顯示/etc/passwd檔案中其預設shell為/bin/bash的使用者

[root@localhost home]# grep "/bin/bash" /etc/passwdView Code

13.找出/etc/passwd檔案中的一位或兩位元

[root@localhost /]# egrep "\<[[:digit:]]{1,2}\>" /etc/passwdView Code

14.顯示/boot/grub2/grup.cfg中至少一個空白字元開頭的行

[root@localhost /]# egrep "^[[:space:]]+[^[:space:]]" /boot/grub2/grub.cfg View Code

15.顯示/etc/rc.d/rc.local檔案中以#開頭,後面跟至少一個空白字元,而後又至少一個非空白字元的行

[root@localhost /]# egrep "^#[[:space:]]+[^[:space:]]" /etc/rc.d/rc.local # THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES# It is highly advisable to create own systemd services or udev rules# to run scripts during boot instead of using this file.# In contrast to previous versions due to parallel execution during boot# this script will NOT be run after all other services.# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure# that this script will be executed during boot.View Code

16.打出netstat -tan命令執行結果以'LISTEN'後跟空白字元結尾的行

[root@localhost /]# netstat -tan | egrep "LISTEN[[:space:]]+"tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN tcp6 0 0 :::111 :::* LISTEN tcp6 0 0 :::22 :::* LISTEN tcp6 0 0 ::1:631 :::* LISTEN tcp6 0 0 ::1:25 :::* LISTEN View Code

17.添加使用者bash,testbash,basher,nologin(此一個使用者的shell為/sbin/nologin),而後找出當前系統上其使用者名稱和預設shell相同的使用者的資訊

[root@localhost /]# useradd bash[root@localhost /]# useradd testbash[root@localhost /]# useradd basher[root@localhost /]# useradd -s /sbin/nologin nologin[root@localhost /]# egrep "^(\<[a-z]+\>).*\1$" /etc/passwdsync:x:5:0:sync:/sbin:/bin/syncshutdown:x:6:0:shutdown:/sbin:/sbin/shutdownhalt:x:7:0:halt:/sbin:/sbin/haltbash:x:2004:2004::/home/bash:/bin/bashnologin:x:2007:2007::/home/nologin:/sbin/nologinView Code

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.