1. 程式人生 > >grep正則表達式使用10例

grep正則表達式使用10例

linux

1、顯示/etc/passwd文件中不以/bin/bash結尾的行

[[email protected]~]# grep -v"/bin/bash$" /etc/passwd

bin:x:1:1:bin:/bin:/sbin/nologin

daemon:x:2:2:daemon:/sbin:/sbin/nologin

adm:x:3:4:adm:/var/adm:/sbin/nologin

lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

sync:x:5:0:sync:/sbin:/bin/sync

2、找出/etc/passwd文件中的兩位數或三位數

[[email protected]~]# grep"\<[0-9]\{2,3\}\>" /etc/passwd

mail:x:8:12:mail:/var/spool/mail:/sbin/nologin

operator:x:11:0:operator:/root:/sbin/nologin

games:x:12:100:games:/usr/games:/sbin/nologin

ftp:x:14:50:FTPUser:/var/ftp:/sbin/nologin

nobody:x:99:99:Nobody:/:/sbin/nologin

systemd-bus-proxy:x:999:998:systemdBus Proxy:/:/sbin/nologin

3、找出/etc/rc.d/rc/rc.sysinit文件中,以至少一個空白字符開頭,且後面非空白字符的行

[[email protected]~]# grep"^[[:space:]]\+[^[:space:]]" /etc/rc.d/rc.sysinit

. /etc/sysconfig/network

HOSTNAME=localhost

mount -n -t proc /proc /proc

mount -n -t sysfs /sys /sys>/dev/null 2>&1

4、找出 netstat -tan 命令的結果以 “LISTEN” 後跟0、1或多個空白字符結尾的行

[[email protected]~]# netstat -tan|grep"LISTEN[[:space:]]*$"

tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN

tcp 0 0 :::22 :::* LISTEN

5、找出/proc/meminfo文件中,所有在大寫或小寫s開頭的行,用3種方式

[[email protected]~]# grep ^[sS] /proc/meminfo

SwapCached: 0 kB

SwapTotal: 2097148 kB

SwapFree: 2097148 kB

[[email protected]~]# grep -E "^(s|S)"/proc/meminfo

SwapCached: 0 kB

SwapTotal: 2097148 kB

SwapFree: 2097148 kB

[[email protected]~]# grep -E "^s|^S"/proc/meminfo

SwapCached: 0 kB

SwapTotal: 2097148 kB

SwapFree: 2097148 kB

6、顯示當前系統上root、centos、或user1用戶的相關信息

[[email protected] ~]# grep -E "^(root|centos|user1)\>" /etc/passwd

root:x:0:0:root:/root:/bin/bash

centos:x:1003:1005::/home/centos:/bin/bash

user1:x:1004:1006::/home/user1:/bin/bash

7、找出/etc/rc.d/init.d/functions文件中某單詞後面跟一個小括號的行

[[email protected]~]# grep -E"[[:alpha:]]+\(\)" /etc/rc.d/init.d/functions

checkpid() {

__kill_pids_term_kill_checkpids(){

__kill_pids_term_kill(){

8、使用echo命令輸出一絕對路徑,取出基名

[[email protected]~]# echo"/etc/rc.d/init.d/functions"|grep -oE "[^/]+$"

functions

9、找出ifconfig命令結果中1-255之間的數值

[[email protected]~]# ifconfig|grep -oE"\<([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>"

192

168

168

130

255

255

255

10、添加用戶bash、testbash、basher以及nologin(其shell為/sbin/nologin);然後找出/etc/passwd文件中用戶名和shell名一樣的行

[[email protected]~]# cat /etc/passwd|grep -E"^(.*):.*/\1$"

sync:x:5:0:sync:/sbin:/bin/sync

shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

halt:x:7:0:halt:/sbin:/sbin/halt

bash:x:1005:1007::/home/bash:/bin/bash

nologin:x:1008:1010::/home/nologin:/sbin/nologin

法2:

[[email protected]~]# cat /etc/passwd|grep -E"^([^:]+\>).*\1$"

sync:x:5:0:sync:/sbin:/bin/sync

shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

halt:x:7:0:halt:/sbin:/sbin/halt

bash:x:1005:1007::/home/bash:/bin/bash

nologin:x:1008:1010::/home/nologin:/sbin/nologin


grep正則表達式使用10例