《LINUX教學:Linux的正則表達式grep,egrep》要點:
本文介紹了LINUX教學:Linux的正則表達式grep,egrep,希望對您有用。如果有疑問,可以聯系我們。
一、觀點
正則表達式是對字符串操作的一種邏輯公式,用事先定義好的一組特殊字符,組成一個“規則字符集合”,根據用戶指定的文本模式對目標文件進行逐行搜索匹配,顯示能被模式匹配到的成果.
給定一個正則表達式和另一個目標字符串,我們可以從給定的字符串中通過匹配模型,過濾字符串中不想要的的字符串,得到目標字符串,減少工作量.
常用的正則表達式一般分為基本正則表達式grep和擴展正則表達式egrep.
二、基本正則表達式grep
根本正則表達式grep: Global search Regular Expression and Print out of the line
用法:
grep [options] "pattern" file
常用選項
--color=auto 匹配到的字符串顯示顏色
-v 反向匹配,顯示不能被匹配到的行
-o 僅顯示行中被模式匹配到的字符串
-i 忽略大小寫(ignore case)
-n 顯示行號
-c 顯示統計到的行號,等同于wc -l
-q 靜默模式,不輸出任何信息
-e 一次匹配多個條件
-w 匹配整個單詞
-A(after) 顯示匹配到的行以及下面的一行
-B(before) 顯示匹配到的行以及上面的一行
-C(context) 顯示匹配到的行以及上下各一行
-E 支持擴展正則表達式
grep -E =egrep
元字符
元字符:*,?,不表示字符自己的意義,而是用于額外功能性的描述;
. 匹配任意單個字符
* 匹配任意字符任意次
.* 匹配任意長度的任意字符
\? 匹配其前面的字符0次或1次
[] 指定范圍內的任意單個字符
[[:alpha:]] 匹配所有的大寫字母和小寫字母
[[:digit:]] 匹配所有的數字
[[:lower:]] 匹配小寫字母
[[:upper:]] 匹配大寫字母
[[:alnum:]] 匹配大小寫字母和數字
[[:graph:]] 匹配所有非空格字符串
[[:space:]] 匹配空格
[[:punct:]] 匹配標點符號
[[:print:]] 匹配所有可打印的字母
[^] 指定范圍外的任意單個字符
\{m\} 匹配m次
\{m,n\} 匹配最少m次,最多n次
\{m,\} 匹配最少m次
\{0,n\} 匹配最多n次
^ 匹配行首(必需出現在行首)
$ 匹配行尾(必需出現在行尾)
^$ 錨定空白行
^char 錨定行首
char$ 錨定行尾
\< \b 錨定詞首
\> \b 錨定詞尾
\(\) 分組
\1 匹配前面第一個小括號內的模式相同的內容
\(ab\)\{1,3\}: ab,aab,abb,abab,ababab
\(a.b\).*\1 前匹配后引用
三、擴展正則表達式
相稱于 grep -E
元字符:
字符匹配:
. 任意單個字符
[] 指定規模內的任意單個字符
[^] 指定規模外的任意單個字符
次數匹配:
* 匹配其前面的字符任意次
? 匹配其前面的字符0次或1次
+ 匹配其前面的字符至少1次
{m} 匹配其前面的字符m次
{m,n} 匹配其前面的字符最少m次最多n次
{m,} 匹配其前面的字符最少m次
{0,n} 匹配其前面的字符最多n次
錨定:
^ 錨定行首
$ 錨定行尾
\< \b 錨定單詞首部
\> \b 錨定單詞尾部
分組:
() 分組
| 同時匹配,同時匹配其前面和其后面的字符
練習:
1.找出/etc/passwd中的兩位數或三位數
[root@pxe40 ~]#grep "[[:digit:]]\{2,3\}" /etc/passwd
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
gopher:x:13:30:gopher:/var/gopher:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin
saslauth:x:499:76:Saslauthd user:/var/empty/saslauth:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
2.顯示CentOS7中/etc/grub2.cfg文件中,至少以一個空白字符串開首且后在存在非空白字符的行
[root@localhost ~]#egrep "^[[:space:]]{1,}[^[: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
if [ -z "${boot_once}" ]; then
saved_entry="${chosen}"
save_env saved_entry
fi
if [ x$feature_all_video_module = xy ]; then
insmod all_video
else
insmod efi_gop
insmod efi_uga
insmod ieee1275_fb
insmod vbe
insmod vga
insmod video_bochs
insmod video_cirrus
fi
set timeout_style=menu
set timeout=5
set timeout=5
source ${prefix}/user.cfg
if [ -n ${GRUB2_PASSWORD} ]; then
set superusers="root"
export superusers
password_pbkdf2 root ${GRUB2_PASSWORD}
fi
load_video
set gfxpayload=keep
insmod gzio
insmod part_msdos
insmod xfs
set root='hd0,msdos1'
if [ x$feature_platform_search_hint = xy ]; then
search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=ahci0,msdos1 --hint='hd0,msdos1' 0f3b795b-fc0b-45a0-becd-38fb57482121
else
search --no-floppy --fs-uuid --set=root 0f3b795b-fc0b-45a0-becd-38fb57482121
fi
linux16 /vmlinuz-3.10.0-327.el7.x86_64 root=UUID=844cc1df-258f-4258-8f38-94de51387be9 ro rhgb quiet LANG=en_US.UTF-8
initrd16 /initramfs-3.10.0-327.el7.x86_64.img
load_video
insmod gzio
insmod part_msdos
insmod xfs
set root='hd0,msdos1'
if [ x$feature_platform_search_hint = xy ]; then
search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=ahci0,msdos1 --hint='hd0,msdos1' 0f3b795b-fc0b-45a0-becd-38fb57482121
else
search --no-floppy --fs-uuid --set=root 0f3b795b-fc0b-45a0-becd-38fb57482121
fi
linux16 /vmlinuz-0-rescue-e2ddeae13fe64821ae46c7feca0669ae root=UUID=844cc1df-258f-4258-8f38-94de51387be9 ro rhgb quiet
initrd16 /initramfs-0-rescue-e2ddeae13fe64821ae46c7feca0669ae.img
source ${config_directory}/custom.cfg
source $prefix/custom.cfg;
3.顯示/etc/passwd文件中包括root內容的行
[root@pxe40 ~]#grep "root" /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
4.找出/etc/passwd文件中以root開首以bash結尾的行
[root@pxe40 ~]#grep "^root.*bash$" /etc/passwd
root:x:0:0:root:/root:/bin/bash
5.打出/etc/passwd文件中不因此/sbin/nologin結尾的行,并顯示該用戶在文件中的行號
[root@pxe40 ~]#cat -n /etc/passwd | grep "nologin$"
2 bin:x:1:1:bin:/bin:/sbin/nologin
3 daemon:x:2:2:daemon:/sbin:/sbin/nologin
4 adm:x:3:4:adm:/var/adm:/sbin/nologin
5 lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
9 mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
10 uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
11 operator:x:11:0:operator:/root:/sbin/nologin
12 games:x:12:100:games:/usr/games:/sbin/nologin
13 gopher:x:13:30:gopher:/var/gopher:/sbin/nologin
14 ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
15 nobody:x:99:99:Nobody:/:/sbin/nologin
16 vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin
17 saslauth:x:499:76:Saslauthd user:/var/empty/saslauth:/sbin/nologin
18 postfix:x:89:89::/var/spool/postfix:/sbin/nologin
19 sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
6.找出/etc/passwd文件中shutdown用戶地點的行以及上下各三行內容
[root@pxe40 ~]#grep -C 3 "shutdown" /etc/passwd
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
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
7.找出/root/.bashrc文件中不包括注釋和空白的行
[root@pxe40 ~]#egrep -v "^#|^$" .bashrc
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
alias "cdnet"="cd /etc/sysconfig/network-scripts/"
alias "grep"="grep --color=auto"
alias vi=vim
8.找出/etc/passwd文件中用戶id和屬組id雷同的用戶
[root@pxe40 ~]#grep "\(\b[[:digit:]]\{1,5\}\b\).*\1" /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
9.顯示/proc/meminfo文件中以年夜小寫s開頭的行
[root@pxe40 ~]#grep -i "^s" /proc/meminfo
SwapCached: 0 kB
SwapTotal: 2047996 kB
SwapFree: 2047996 kB
Shmem: 240 kB
Slab: 68740 kB
SReclaimable: 10556 kB
SUnreclaim: 58184 kB
10.掏出系統中默認shell為非bash的用戶
[root@pxe40 ~]#grep -v "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
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
gopher:x:13:30:gopher:/var/gopher:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin
saslauth:x:499:76:Saslauthd user:/var/empty/saslauth:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
11.顯示/etc/rc.d/rc.sysinit文件中以#開頭,后面跟最少一個空白字符,爾后又有一個非空白字符的行
[root@pxe40 ~]#egrep "^#[[:space:]]+[^[:space:]]" /etc/rc.d/rc.sysinit
# /etc/rc.d/rc.sysinit - run once at boot time
# Taken in part from Miquel van Smoorenburg's bcheckrc.
# Check SELinux status
# Print a text banner.
# Only read this once.
# Initialize hardware
# Set default affinity
# Load other user-defined modules
# Load modules (for backward compatibility with VARs)
# Configure kernel parameters
# Set the hostname.
# Sync waiting for storage.
# Device mapper & related initialization
# Start any MD RAID arrays that haven't been started yet
# Remount the root filesystem read-write.
# Clean up SELinux labels
# If relabeling, relabel mount points.
# Mount all other filesystems (except for NFS and /proc, which is already
# mounted). Contrary to standard usage,
# filesystems are NOT unmounted in single user mode.
# The 'no' applies to all listed filesystem types. See mount(8).
# Check to see if a full relabel is needed
# Update quotas if necessary
# Initialize pseudo-random number generator
# Configure machine if necessary.
# Clean out /.
# Do we need (w|u)tmpx files? We don't set them up, but the sysadmin might...
# Clean up /var.
# Clean up utmp/wtmp
# Clean up various /tmp bits
# Make ICE directory
# Start up swapping.
# Set up binfmt_misc
# Boot time profiles. Yes, this should be somewhere else.
# Now that we have all of our basic modules loaded and the kernel going,
# let's dump the syslog ring somewhere so we can find it later
# create the crash indicator flag to warn on crashes, offer fsck with timeout
# Let rhgb know that we're leaving rc.sysinit
12.添加用戶bash和testbash,爾后找出系統上其用戶名和默認shell相同的用戶
[root@pxe40 ~]#grep "^\(\b[[:alnum:]]\+\b\).*\1$" /etc/passwd
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:500:500::/home/bash:/bin/bash
本文永遠更新鏈接地址:
學習更多LINUX教程,請查看站內專欄,如果有LINUX疑問,可以加QQ交流《LINUX教學:Linux的正則表達式grep,egrep》。