本文共 10171 字,大约阅读时间需要 33 分钟。
一、概念
正则表达式是对字符串操作的一种逻辑公式,用事先定义好的一组特殊字符,组成一个“规则字符集合”,根据用户指定的文本模式对目标文件进行逐行搜索匹配,显示能被模式匹配到的结果。给定一个正则表达式和另一个目标字符串,我们可以从给定的字符串中通过匹配模型,过滤字符串中不想要的的字符串,得到目标字符串,减少工作量。常用的正则表达式一般分为基本正则表达式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/passwdmail:x:8:12:mail:/var/spool/mail:/sbin/nologinuucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologinoperator:x:11:0:operator:/root:/sbin/nologingames:x:12:100:games:/usr/games:/sbin/nologingopher:x:13:30:gopher:/var/gopher:/sbin/nologinftp:x:14:50:FTP User:/var/ftp:/sbin/nologinnobody:x:99:99:Nobody:/:/sbin/nologinvcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologinsaslauth:x:499:76:Saslauthd user:/var/empty/saslauth:/sbin/nologinpostfix:x:89:89::/var/spool/postfix:/sbin/nologinsshd: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/passwdroot:x:0:0:root:/root:/bin/bashoperator:x:11:0:operator:/root:/sbin/nologin
4.找出/etc/passwd文件中以root开头以bash结尾的行
[root@pxe40 ~]#grep "^root.*bash$" /etc/passwdroot: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/nologin10 uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin11 operator:x:11:0:operator:/root:/sbin/nologin12 games:x:12:100:games:/usr/games:/sbin/nologin13 gopher:x:13:30:gopher:/var/gopher:/sbin/nologin14 ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin15 nobody:x:99:99:Nobody:/:/sbin/nologin16 vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin17 saslauth:x:499:76:Saslauthd user:/var/empty/saslauth:/sbin/nologin18 postfix:x:89:89::/var/spool/postfix:/sbin/nologin19 sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
6.找出/etc/passwd文件中shutdown用户所在的行以及上下各三行内容
[root@pxe40 ~]#grep -C 3 "shutdown" /etc/passwdadm: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/shutdownhalt:x:7:0:halt:/sbin:/sbin/haltmail:x:8:12:mail:/var/spool/mail:/sbin/nologinuucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
7.找出/root/.bashrc文件中不包含注释和空白的行
[root@pxe40 ~]#egrep -v "^#|^$" .bashrcalias rm='rm -i'alias cp='cp -i'alias mv='mv -i'if [ -f /etc/bashrc ]; then . /etc/bashrcfialias "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/passwdroot:x:0:0:root:/root:/bin/bashbin:x:1:1:bin:/bin:/sbin/nologindaemon:x:2:2:daemon:/sbin:/sbin/nologinnobody:x:99:99:Nobody:/:/sbin/nologinvcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologinpostfix:x:89:89::/var/spool/postfix:/sbin/nologinsshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
9.显示/proc/meminfo文件中以大小写s开头的行
[root@pxe40 ~]#grep -i "^s" /proc/meminfoSwapCached: 0 kBSwapTotal: 2047996 kBSwapFree: 2047996 kBShmem: 240 kBSlab: 68740 kBSReclaimable: 10556 kBSUnreclaim: 58184 kB
10.取出系统中默认shell为非bash的用户
[root@pxe40 ~]#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/shutdownhalt:x:7:0:halt:/sbin:/sbin/haltmail:x:8:12:mail:/var/spool/mail:/sbin/nologinuucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologinoperator:x:11:0:operator:/root:/sbin/nologingames:x:12:100:games:/usr/games:/sbin/nologingopher:x:13:30:gopher:/var/gopher:/sbin/nologinftp:x:14:50:FTP User:/var/ftp:/sbin/nologinnobody:x:99:99:Nobody:/:/sbin/nologinvcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologinsaslauth:x:499:76:Saslauthd user:/var/empty/saslauth:/sbin/nologinpostfix:x:89:89::/var/spool/postfix:/sbin/nologinsshd: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/passwdsync:x:5:0:sync:/sbin:/bin/syncshutdown:x:6:0:shutdown:/sbin:/sbin/shutdownhalt:x:7:0:halt:/sbin:/sbin/haltbash:x:500:500::/home/bash:/bin/bash
转载地址:http://kqykl.baihongyu.com/