正则表达式

概述

概念

正则表达式是你所定义的模式模板, Linux工具可以用它来过滤文本。 Linux 工具(比如sed编辑器或gawk程序)
能够在处理数据时使用正则表达式对数据进行模式匹配。如果数据匹配模式,它就会被接受并进一步处理;
如果数据不匹配模式,它就会被滤掉。

数据流–正则表达式—(1)匹配的数据 (2)滤掉的数据

正则表达式(或称Regular Expression,简称RE),是用于描述字符排列和匹配模式的一种语法规则。
它主要用于字符串的分割,匹配、査找及替换操作。即正则表达式是一种文本模式,该模式描述在搜索文本时要匹配的一个或多个字符串

简单来说就是通过一些特殊字符的排序,用以删除、查找、替换一行或者多行文字字符串的程序。

作用

通常用于判断语句中,用来检查某一字符串是否满足某一格式
正则表达式是由普通字符与元字符组成
普通字符包括大小写字母、数字、标点符号及一些其他符号
元字符是指在正则表达式中具有特殊意义的专用字符,可以用来规定其前导字符(即位于元字符前面的字符)在目标对象中的出现模式

可达到的目的
给定一个正则表达式和另一个字符串,我们可以达到如下的目的:
(1)给定的字符串是否符合正则表达式的过滤逻辑(称作匹配)
(2)可以通过正则表达式,从字符串中获取我们想要的特定部分

基础正则

1、基础正则常见元字符(支付的工具:grep、egrep、sed、awk)

\ :转义字符,用于取消特殊符号的含义,例:\! 、\n、\$等
^ :匹配字符串开始的位置,例:^a、^the、^#、^[a-z]
$ :匹配字符串结束的位置,例: word$、 ^$匹配空行
. :匹配除\n之外的任意的一个字符,例: lo.*k、lo.k、l..k
* : 匹配前面一个字符出现0次或者多次,例: loo*k、lo*k
[list] : 匹配list列表中的一个字符,例: go[ola]d, [abc]、 [a-z]、 [a-z0-9]、 [0-9]匹配任意一位数字
[^list] : 匹配任意非list列表中的一个字符,例: [^0-9]、[^A-Z0-9]、 [^a-z]匹配任意一位非小写字母
\{n\} : 匹配前面一个字符n次,例: lo\{2\}k、 '[0-9]\{2\}'匹配两位数字
\{n,\} : 匹配前面一个字符不少于n次,例: lo\{2,\}k、 '[0-9]\{2,\}'匹配两位及两位以上数字
\{n,m\} : 匹配前面一个字符n到m次,例: lo\{2,3\}k、 '[0-9]\{2,3\}'匹配两位到三位数字

注: egrep、 awk使用{n}、{n,}、 {n, m}匹配时“{}"前不用加“\”

1、*匹配前面一个字符0次或者多次

[root@rhel8 ~]# cat a.txt 
lk
lok
look
loook
looooook
loooooaaak
looooooook
abbbbcd
abbbbcd666
ooooloooook
oooooolk
aoblck
[root@rhel8 ~]# grep "loo*k" a.txt
lok
look
loook
looooook
looooooook
ooooloooook
[root@rhel8 ~]#
[root@rhel8 ~]# grep "lo*k" a.txt
lk
lok
look
loook
looooook
looooooook
ooooloooook
oooooolk

2、. 匹配除\n之外的任意的一个字符

[root@rhel8 ~]# grep "lo.*k" a.txt 
lok
look
loook
looooook
loooooaaak
looooooook
ooooloooook
[root@rhel8 ~]# grep "lo.*k" a.txt 
lok
look
loook
looooook
loooooaaak
looooooook
ooooloooook
[root@rhel8 ~]# grep "lo.k" a.txt
look
[root@rhel8 ~]# grep "l..k" a.txt
look

3、
{n} :匹配前面的一个字符出现n次
{n,} :匹配前面的一个字符出现不少于n次
{n,m} :匹配前面的一个字符出现n到m次

[root@rhel8 ~]# grep "lo\{2\}k" a.txt 
look
[root@rhel8 ~]# grep "lo\{3\}k" a.txt 
loook
[root@rhel8 ~]# grep "lo\{3,\}k" a.txt 
loook
looooook
looooooook
ooooloooook
[root@rhel8 ~]# grep "lo\{3,5\}k" a.txt 
loook
ooooloooook
[root@rhel8 ~]#

4、
^ 匹配字符串开始的位置
$ 匹配字符串结束的位置
^$ 匹配空行

[root@rhel8 ~]# cat b.txt 
aa
 
abd
cdd
cdc
cdd
[root@rhel8 ~]#
[root@rhel8 ~]# grep "^c" b.txt 
cdd
cdc
cdd
[root@rhel8 ~]# grep "d$" b.txt 
abd
cdd
cdd
[root@rhel8 ~]# grep "^$" b.txt 
[root@rhel8 ~]# 

5、[list] 匹配list列表中的一个字符

[^list]  匹配任意非list列表中的一个字符
[root@rhel8 ~]# cat c.txt 
lok
lo12k
lo1k
loAk
loBk
look
loak
lodk
abcd
1234
[root@rhel8 ~]# grep "lo[a-zA-Z0-9]k" c.txt 
lo1k
loAk
loBk
look
loak
lodk
[root@rhel8 ~]# grep "lo[ABo]k" c.txt 
loAk
loBk
look
[root@rhel8 ~]# grep "lo[^a-zA-Z]k" c.txt 
lo1k
[root@rhel8 ~]# grep "[^a-zA-Z]" c.txt 
lo12k
lo1k
1234

扩展正则

+ : 匹配前面一个字符1次以上,例: lo+k, 将匹配至少一个o,如lok、look、loook等
 
? : 匹配前面一个字符0次或者1次,例: lo?k,将匹配lk或lok
 
() : 将括号中的字符串作为一个整体,例: l(oo)+k, 将匹配oo整体1次以上,如look、looook等
 
| : 以或的方式匹配字条串,例: l(oo|ab)k, 将匹配look或者labk
{} :允许为可重复的正则表达式指定一个上限,这通常称为间隔(interval)
    {n} 重复n次;{n,} 重复n次或更多次;{n,m} 重复n到m次 
1、+  匹配前面一个字符1次以上
[root@rhel8 ~]# egrep "lo+k" a.txt 
lok
look
loook
looooook
looooooook
ooooloooook

2、 ?  匹配前面一个字符0次或者1次
[root@rhel8 ~]# egrep "lo?k" a.txt 
lk
lok
oooooolk

3、()  将括号中的字符串作为一个整体
[root@rhel8 ~]# egrep "l(oo)+k" a.txt 
look
looooook
looooooook

4、|  以或的方式匹配字条串
[root@rhel8 ~]# echo labk >> a.txt
[root@rhel8 ~]# egrep "l(oo|ab)+k" a.txt 
look
looooook
looooooook
labk

5、{} 允许为可重复的正则表达式指定一个上限
{n} 重复n次;{n,} 重复n次或更多次;{n,m} 重复n到m次
[root@rhel8 ~]# egrep "lo{3}k" a.txt 
loook
[root@rhel8 ~]# egrep "lo{3,}k" a.txt 
loook
looooook
looooooook
ooooloooook
[root@rhel8 ~]# egrep "lo{3,5}k" a.txt 
loook
ooooloooook


特殊的字符组

描 述
[[:alpha:]]匹配任意字母字符,不管是大写还是小写
[[:alnum:]]匹配任意字母数字字符0~9、 AZ或az
[[:blank:]]匹配空格或tab键
[[:digit:]]匹配0~9之间的数字
[[:lower:]]匹配小写字母字符a~z
[[:print:]]匹配任意可打印字符
[[:punct:]]匹配标点符号
[[:space:]]匹配任意空白字符:空格、tab、 NL、 FF、 VT和CR
[[:upper:]]匹配任意大写字母字符A~Z

实例

1.显示/proc/meminfo文件中以大小s开头的行(要求两种方法)

[root@sb ~]# grep ^[s\|S] /proc/meminfo 
SwapCached:            0 kB
SwapTotal:       4124668 kB
SwapFree:        4124668 kB
Shmem:             11064 kB
Slab:             132932 kB
SReclaimable:      54468 kB
#SUnreclaim:        78464 kB
ShmemHugePages:        0 kB
ShmemPmdMapped:        0 kB
[root@sb ~]# 
[root@sb ~]# grep ^[s\S] /proc/meminfo 
SwapCached:            0 kB
SwapTotal:       4124668 kB
SwapFree:        4124668 kB
Shmem:             11064 kB
Slab:             132940 kB
SReclaimable:      54468 kB
SUnreclaim:        78472 kB
ShmemHugePages:        0 kB
ShmemPmdMapped:        0 kB
[root@sb ~]# 

2.显示/etc/passwd文件中不以/bin/bash结尾的行

[root@sb ~]# 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
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
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin
systemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin
tss:x:59:59:Account used for TPM access:/dev/null:/sbin/nologin
polkitd:x:998:996:User for polkitd:/:/sbin/nologin
unbound:x:997:995:Unbound DNS resolver:/etc/unbound:/sbin/nologin
geoclue:x:996:994:User for geoclue:/var/lib/geoclue:/sbin/nologin
rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin
pipewire:x:995:991:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin
pulse:x:171:171:PulseAudio System Daemon:/var/run/pulse:/sbin/nologin
qemu:x:107:107:qemu user:/:/sbin/nologin
usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin
gluster:x:994:988:GlusterFS daemons:/run/gluster:/sbin/nologin
rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
chrony:x:993:987::/var/lib/chrony:/sbin/nologin
saslauth:x:992:76:Saslauthd user:/run/saslauthd:/sbin/nologin
libstoragemgmt:x:991:985:daemon account for libstoragemgmt:/var/run/lsm:/sbin/nologin
dnsmasq:x:984:984:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin
radvd:x:75:75:radvd user:/:/sbin/nologin
sssd:x:983:983:User for sssd:/:/sbin/nologin
cockpit-ws:x:982:982:User for cockpit web service:/nonexisting:/sbin/nologin
cockpit-wsinstance:x:981:981:User for cockpit-ws instances:/nonexisting:/sbin/nologin
colord:x:980:980:User for colord:/var/lib/colord:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
setroubleshoot:x:979:979::/var/lib/setroubleshoot:/sbin/nologin
flatpak:x:978:978:User for flatpak system helper:/:/sbin/nologin
gdm:x:42:42::/var/lib/gdm:/sbin/nologin
clevis:x:977:977:Clevis Decryption Framework unprivileged user:/var/cache/clevis:/sbin/nologin
gnome-initial-setup:x:976:975::/run/gnome-initial-setup/:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
[root@sb ~]# 

3.显示用户rpc默认的shell程序

[root@sb ~]# grep "\(^rpc\)" /etc/passwd | cut -d":" -f7
/sbin/nologin
/sbin/nologin
[root@sb ~]# 

4.找出/etc/passwd中的两位或三位数------ grep -o 只显示匹配的部分

[root@sb ~]# grep -o "[0-9]\{2,3\}" /etc/passwd
12
11
12
100
14
50
655
34
655
34
81
81
999
997
193
193
59
59
998
996
997
995
996
994
172
172
995
991
171
171
107
107
113
113
994
988
32
32
70
70
993
987
992
76
991
985
984
984
75
75
983
983
982
982
981
981
980
980
29
29
979
979
978
978
42
42
977
977
976
975
74
74
72
72
100
100
48
48
[root@sb ~]# 

5.显示centos8的/etc/grub2.cfg文件中,至少以一个空白字符开头且后面有非空白字符的行

[root@sb ~]# grep "[[:space:]]\?\S" /etc/grub2.cfg
#
# DO NOT EDIT THIS FILE
#
# It is automatically generated by grub2-mkconfig using templates
# from /etc/grub.d and settings from /etc/default/grub
#
### BEGIN /etc/grub.d/00_header ###
set pager=1
if [ -f ${config_directory}/grubenv ]; then
  load_env -f ${config_directory}/grubenv
elif [ -s $prefix/grubenv ]; then
  load_env
fi
if [ "${next_entry}" ] ; then
   set default="${next_entry}"
   set next_entry=
   save_env next_entry
   set boot_once=true
else
   set default="${saved_entry}"
fi
if [ x"${feature_menuentry_id}" = xy ]; then
  menuentry_id_option="--id"
else
  menuentry_id_option=""
fi
export menuentry_id_option
if [ "${prev_saved_entry}" ]; then
  set saved_entry="${prev_saved_entry}"
  save_env saved_entry
  set prev_saved_entry=
  save_env prev_saved_entry
  set boot_once=true
fi
function savedefault {
  if [ -z "${boot_once}" ]; then
    saved_entry="${chosen}"
    save_env saved_entry
  fi
}
function load_video {
  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
}
terminal_output console
if [ x$feature_timeout_style = xy ] ; then
  set timeout_style=menu
  set timeout=5
# Fallback normal timeout code in case the timeout_style feature is
# unavailable.
else
  set timeout=5
fi
### END /etc/grub.d/00_header ###
### BEGIN /etc/grub.d/00_tuned ###
set tuned_params=""
set tuned_initrd=""
### END /etc/grub.d/00_tuned ###
### BEGIN /etc/grub.d/01_users ###
if [ -f ${prefix}/user.cfg ]; then
  source ${prefix}/user.cfg
  if [ -n "${GRUB2_PASSWORD}" ]; then
    set superusers="root"
    export superusers
    password_pbkdf2 root ${GRUB2_PASSWORD}
  fi
fi
### END /etc/grub.d/01_users ###
### BEGIN /etc/grub.d/08_fallback_counting ###
insmod increment
# Check if boot_counter exists and boot_success=0 to activate this behaviour.
if [ -n "${boot_counter}" -a "${boot_success}" = "0" ]; then
  # if countdown has ended, choose to boot rollback deployment,
  # i.e. default=1 on OSTree-based systems.
  if  [ "${boot_counter}" = "0" -o "${boot_counter}" = "-1" ]; then
    set default=1
    set boot_counter=-1
  # otherwise decrement boot_counter
  else
    decrement boot_counter
  fi
  save_env boot_counter
fi
### END /etc/grub.d/08_fallback_counting ###
### BEGIN /etc/grub.d/10_linux ###
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=aci0,msdos1 --hint='hd0,msdos1'  4a0b4189-1333-4789-8ef5-123f0c8d8dc5
else
  search --no-floppy --fs-uuid --set=root 4a0b4189-1333-4789-8ef5-123f0c8d8dc5
fi
insmod part_msdos
insmod xfs
set boot='hd0,msdos1'
if [ x$feature_platform_search_hint = xy ]; then
  search --no-floppy --fs-uuid --set=boot --hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=aci0,msdos1 --hint='hd0,msdos1'  4a0b4189-1333-4789-8ef5-123f0c8d8dc5
else
  search --no-floppy --fs-uuid --set=boot 4a0b4189-1333-4789-8ef5-123f0c8d8dc5
fi
# This section was generated by a script. Do not modify the generated file - all changes
# will be lost the next time file is regenerated. Instead edit the BootLoaderSpec files.
#
# The blscfg command parses the BootLoaderSpec files stored in /boot/loader/entries and
# populates the boot menu. Please refer to the Boot Loader Specification documentation
# for the files format: https://www.freedesktop.org/wiki/Specifications/BootLoaderSpec/.
# The kernelopts variable should be defined in the grubenv file. But to ensure that menu
# entries populated from BootLoaderSpec files that use this variable work correctly even
# without a grubenv file, define a fallback kernelopts variable if this has not been set.
#
# The kernelopts variable in the grubenv file can be modified using the grubby tool or by
# executing the grub2-mkconfig tool. For the latter, the values of the GRUB_CMDLINE_LINUX
# and GRUB_CMDLINE_LINUX_DEFAULT options from /etc/default/grub file are used to set both
# the kernelopts variable in the grubenv file and the fallback kernelopts variable.
if [ -z "${kernelopts}" ]; then
  set kernelopts="root=/dev/mapper/cs-root ro crashkernel=auto resume=/dev/mapper/cs-swap rd.lvm.lv=cs/rot rd.lvm.lv=cs/swap rhgb quiet "
fi
insmod blscfg
blscfg
### END /etc/grub.d/10_linux ###
### BEGIN /etc/grub.d/10_reset_boot_success ###
# Hiding the menu is ok if last boot was ok or if this is a first boot attempt to boot the entry
if [ "${boot_success}" = "1" -o "${boot_indeterminate}" = "1" ]; then
  set menu_hide_ok=1
else
  set menu_hide_ok=0 
fi
# Reset boot_indeterminate after a successful boot
if [ "${boot_success}" = "1" ] ; then
  set boot_indeterminate=0
# Avoid boot_indeterminate causing the menu to be hidden more then once
elif [ "${boot_indeterminate}" = "1" ]; then
  set boot_indeterminate=2
fi
# Reset boot_success for current boot 
set boot_success=0
save_env boot_success boot_indeterminate
### END /etc/grub.d/10_reset_boot_success ###
### BEGIN /etc/grub.d/12_menu_auto_hide ###
if [ x$feature_timeout_style = xy ] ; then
  if [ "${menu_show_once}" ]; then
    unset menu_show_once
    save_env menu_show_once
    set timeout_style=menu
    set timeout=60
  elif [ "${menu_auto_hide}" -a "${menu_hide_ok}" = "1" ]; then
    set orig_timeout_style=${timeout_style}
    set orig_timeout=${timeout}
    if [ "${fastboot}" = "1" ]; then
      # timeout_style=menu + timeout=0 avoids the countdown code keypress check
      set timeout_style=menu
      set timeout=0
    else
      set timeout_style=hidden
      set timeout=1
    fi
  fi
fi
### END /etc/grub.d/12_menu_auto_hide ###
### BEGIN /etc/grub.d/20_linux_xen ###
### END /etc/grub.d/20_linux_xen ###
### BEGIN /etc/grub.d/20_ppc_terminfo ###
### END /etc/grub.d/20_ppc_terminfo ###
### BEGIN /etc/grub.d/30_os-prober ###
### END /etc/grub.d/30_os-prober ###
### BEGIN /etc/grub.d/30_uefi-firmware ###
### END /etc/grub.d/30_uefi-firmware ###
### BEGIN /etc/grub.d/35_fwupd ###
### END /etc/grub.d/35_fwupd ###
### BEGIN /etc/grub.d/40_custom ###
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.
### END /etc/grub.d/40_custom ###
### BEGIN /etc/grub.d/41_custom ###
if [ -f  ${config_directory}/custom.cfg ]; then
  source ${config_directory}/custom.cfg
elif [ -z "${config_directory}" -a -f  $prefix/custom.cfg ]; then
  source $prefix/custom.cfg;
fi
### END /etc/grub.d/41_custom ###
[root@sb ~]#

6.找出netstat -tan命令结果中以LISTEN后跟任意多个空白字符结尾的行

[root@sb ~]# netstat -tan | grep '\(LISTEN[[:space:]]*\)$'
tcp        0      0 192.168.122.1:53        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 0.0.0.0:111             0.0.0.0:*               LISTEN     
tcp6       0      0 :::22                   :::*                    LISTEN     
tcp6       0      0 ::1:631                 :::*                    LISTEN     
tcp6       0      0 :::111                  :::*                    LISTEN     
[root@sb ~]# 

7.显示centos8上所有UID小于1000以内的用户名和UID

[root@sb ~]# cat /etc/passwd | cut -d":" -f1,3 | grep -v "[0-9]\{4,\}"
root:0
bin:1
daemon:2
adm:3
lp:4
sync:5
shutdown:6
halt:7
mail:8
operator:11
games:12
ftp:14
dbus:81
systemd-coredump:999
systemd-resolve:193
tss:59
polkitd:998
unbound:997
geoclue:996
rtkit:172
pipewire:995
pulse:171
qemu:107
usbmuxd:113
gluster:994
rpc:32
avahi:70
chrony:993
saslauth:992
libstoragemgmt:991
dnsmasq:984
radvd:75
sssd:983
cockpit-ws:982
cockpit-wsinstance:981
colord:980
rpcuser:29
setroubleshoot:979
flatpak:978
gdm:42
clevis:977
gnome-initial-setup:976
sshd:74
tcpdump:72
apache:48
[root@sb ~]#
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值