mycpen

Mycpen

记录学习历程与受益知识
github
telegram
bilibili

12_Linux基础-SHELL命令-sort-uniq-cut-grep-正则表达式-通配符

一。回顾#

回顾 1 shell 常用命令

获取命令的返回输出结果	
1.` `,反引号	 line=`ls`
2.$()			line=$(ls)
seq 类似于python里的range
主要生产一组有序数字序列
-s 指定分隔符
-w 指定同等宽度输出

二. sort#

sort 命令

  • 默认按每行的第一个字符排序
  • -n:按整数进行排序 --> 默认是升序
  • -r:递减排序(注:降序)
  • -u:去重

指定排序键

  • 指定按哪一列数据进行排序
  • -k:指定哪一列为排序键
  • cat tt | sort -n -k4

指定字段分隔符

  • -t:指定字段分割符(默认是空白)
  • sort -t: -n -k3 /etc/passwd # 注:指定分隔符为 :

sort 是一个排序命令

  • 默认按照每行第一个首字符进行排序
    • 英文根据 a-z 的顺序进行排序,如果第一个字母相同,就比较第二个字母,依次类推
    • 中文根据首个字符的拼音的首字母进行排序
示例1:cat sort_test.txt |sort
---------------------------------------------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# cat sort_test.txt 			# 注:显示文本内容
中文 456 1xx  123
abc bcd  3yy dd
Aac XYZ  2zz
三创 xixi
[root@sanchuang-linux ~]# cat sort_test.txt |sort		# 注:对整个文本进行排序
三创 xixi
中文 456 1xx  123
Aac XYZ  2zz
abc bcd  3yy dd
--------------------------------------------------------------------------------------------
>>> ord("三")							# python中的ord()函数查看万国码编码
19977									# 注:sort不是按编码排序
>>> ord("中")
20013
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# locale		# 注:查看编码格式
LANG=zh_CN.UTF-8
LC_CTYPE="zh_CN.UTF-8"
LC_NUMERIC="zh_CN.UTF-8"
LC_TIME="zh_CN.UTF-8"
LC_COLLATE="zh_CN.UTF-8"
LC_MONETARY="zh_CN.UTF-8"
LC_MESSAGES="zh_CN.UTF-8"
LC_PAPER="zh_CN.UTF-8"
LC_NAME="zh_CN.UTF-8"
LC_ADDRESS="zh_CN.UTF-8"
LC_TELEPHONE="zh_CN.UTF-8"
LC_MEASUREMENT="zh_CN.UTF-8"
LC_IDENTIFICATION="zh_CN.UTF-8"
LC_ALL=
============================================================================================
示例2:cat sort_test.txt |sort -k 2	指定哪一列为排序键
[root@sanchuang-linux ~]# cat sort_test.txt |sort -k2		# 注:指定第二列进行排序
中文 456 1xx  123
abc bcd  3yy dd
三创 xixi
Aac XYZ  2zz
[root@sanchuang-linux ~]# cat sort_test.txt |sort -k 3	  # 注:指定第三列进行排序
三创 xixi													# 注:空白在前面
中文 456 1xx  123											# 注:1
Aac XYZ  2zz											 # 注:2
abc bcd  3yy dd											 # 注:3
============================================================================================
示例3:英文根据a-z的顺序进行排序,如果第一个字母相同,就比较第二个字母
[root@sanchuang-linux ~]# cat sort_test.txt 
中文 456 1xx  123
aac bcd  3yy dd
Aac XYZ  2zz
三创 xixi
Xyz  cde
Bbc  Abc
bbc xxx
ABC
abc
[root@sanchuang-linux ~]# cat sort_test.txt |sort			# 注:不是按照编码排序
三创 xixi
中文 456 1xx  123
aac bcd  3yy dd
Aac XYZ  2zz
abc
ABC
Bbc  Abc
bbc xxx
Xyz  cde

sort -n#

sort -n 按数字进行排序

[root@sanchuang-linux ~]# a=123						# 注:a表示的是字符
[root@sanchuang-linux ~]# b=234
[root@sanchuang-linux ~]# echo $a+$b				# 注:字符串的拼接
123+234
[root@sanchuang-linux ~]# echo $(($a+$b))			# 注:需要用2个括号进行数字的相加
357
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# cat aa.txt 
123
23
4
234
[root@sanchuang-linux ~]# cat aa.txt |sort			# 注:默认情况按首个字母字符串进行排序
123
23
234
4
[root@sanchuang-linux ~]# cat aa.txt |sort -n		# 注:sort -n 按数值大小进行排序
4													# 注:默认升序
23													# 注:-n 数字排序比较
123
234
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# cat aa.txt |sort -n -r	# 注:数字、倒序 排序,效果相同
[root@sanchuang-linux ~]# cat aa.txt |sort -nr		# 注:数字、倒序 排序,效果相同
234
123
23
4

-t 指定列数的分隔符#

指定列数的分隔符 # head -n7 /etc/passwd |sort -k6 -t :

默认分隔符为空白字符

使用 -t 指定列数的分隔符

[root@sanchuang-linux ~]# head -n7 /etc/passwd |sort		# 注:取前7行 排序
adm:x:3:4:adm:/var/adm:/sbin/nologin
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
root:x:0:0:root:/root:/bin/bash
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
sync:x:5:0:sync:/sbin:/bin/sync
[root@sanchuang-linux ~]# head -n7 /etc/passwd |sort -k2	# 注:sort -k2指定第2列为排序键
adm:x:3:4:adm:/var/adm:/sbin/nologin
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
root:x:0:0:root:/root:/bin/bash
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
sync:x:5:0:sync:/sbin:/bin/sync
[root@sanchuang-linux ~]# head -n7 /etc/passwd |sort -k6 -t :			# *注:-t : 指定分隔符为 :
bin:x:1:1:bin:/bin:/sbin/nologin
root:x:0:0:root:/root:/bin/bash
sync:x:5:0:sync:/sbin:/bin/sync
daemon:x:2:2:daemon:/sbin:/sbin/nologin
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
[root@sanchuang-linux ~]# head -n7 /etc/passwd |sort -k6 -t : -r		# 注:-r 倒序

三。练习:找出内存使用率最高的 5 个进程#

找出内存使用率最高的 5 个进程

ps aux|sort -n -k4 -r|head -5		注:推荐
注:内存使用率 %MEM
[root@sanchuang-linux ~]# ps aux|tail -n +2|sort -nr -k4 |head -5
root         960  0.0  2.0 221572 38096 ?        S    08:31   0:00 /usr/libexec/sssd/sssd_nss --uid 0 --gid 0 --logger=files
root         930  0.0  1.7 425416 31480 ?        Ssl  08:31   0:01 /usr/libexec/platform-python -Es /usr/sbin/tuned -l -P
polkitd      890  0.0  1.2 1625936 23856 ?       Ssl  08:31   0:00 /usr/lib/polkit-1/polkitd --no-debug
root         891  0.0  0.9 391216 18088 ?        Ssl  08:31   0:00 /usr/sbin/NetworkManager --no-daemon
root         954  0.0  0.8 219700 15416 ?        S    08:31   0:00 /usr/libexec/sssd/sssd_be --domain implicit_files --uid 0 --gid 0 --logger=files
--------------------------------------------------------------------------------------------
#ps aux|tail -n +2|sort -nr -k4 |head -5
注:tail -n +2 显示从第2行到末尾(可加可不加)
注:sort -nr -k4   -n按数字排序,-r倒序,-k4指定第4列为排序键
注:head -5 取前5行

四. uniq#

uniq 命令的使用(去重)

uniq --> unique 唯一的
去重相邻的行
先排序,再去重
-c 统计重复出现的次数
-u 显示只出现 1 次的行
-d 显示重复出现的行

============================================================================================
示例1:去重相邻的行
[root@sanchuang-linux ~]# cat uniq_test.txt
123 abc
abc 123
45
46
45
45
47
47
48
47
[root@sanchuang-linux ~]# cat uniq_test.txt |uniq		# 注:去重相邻的行
123 abc
abc 123
45
46
45
47
48
47
[root@sanchuang-linux ~]# cat uniq_test.txt |sort -n |uniq	# 注:先排序,再去重
abc 123														# 注:一般来说,先排序,再去重
45
46
47
48
123 abc
--------------------------------------------------------------------------------------------
示例1.1 # cat uniq_test.txt |sort -nu
[root@sanchuang-linux ~]# cat uniq_test.txt |sort -n -u		# 注:sort -u 也可以去重
[root@sanchuang-linux ~]# cat uniq_test.txt |sort -nu		# 注:效果一样
abc 123
45
46
47
48
123 abc
============================================================================================
示例2:-c 统计重复出现
[root@sanchuang-linux ~]# cat uniq_test.txt |sort -n |uniq -c    # 注: -c 统计重复出现的次数
      1 abc 123
      3 45
      1 46
      3 47
      1 48
      1 123 abc
============================================================================================
示例3:-u显示只出现1次的行
[root@sanchuang-linux ~]# cat uniq_test.txt |sort -n |uniq -u	# 注:-u显示只出现1次的行
abc 123
46
48
123 abc
============================================================================================
示例4:-d 显示重复出现的行
[root@sanchuang-linux ~]# cat uniq_test.txt |sort -n |uniq -d	# 注:-d 显示重复出现的行
45
47

五。练习:统计 120000 行 频率前十的 ip#

统计 120000 行 频率前十的 ip

[root@sanchuang-linux ~]# cat ips.txt |sort |uniq -c|sort -nr |head
#注1:第一个sort 把相同的ip段放在一起
#注2:uniq -c统计次数
#注:第二个sort -nr 对前面的次数+ip 进行逆序
#注:head 默认取前十个
 :sort -c 用于统计ip地址的访问
[root@localhost ~]# yum install nginx
[root@sanchuang-linux ~]# nginx
[root@sanchuang-linux ~]# lsof -i:80			# 注:nginx起来了
COMMAND   PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
nginx   12765  root    9u  IPv4  60060      0t0  TCP *:http (LISTEN)
nginx   12765  root   10u  IPv6  60061      0t0  TCP *:http (LISTEN)
nginx   12766 nginx    9u  IPv4  60060      0t0  TCP *:http (LISTEN)
nginx   12766 nginx   10u  IPv6  60061      0t0  TCP *:http (LISTEN)
nginx   12767 nginx    9u  IPv4  60060      0t0  TCP *:http (LISTEN)
nginx   12767 nginx   10u  IPv6  60061      0t0  TCP *:http (LISTEN)
[root@sanchuang-linux ~]# iptables -F			# 注:关闭防火墙

[root@sanchuang-linux ~]# cd /var/log			# 注:/var/log放日志
[root@sanchuang-linux log]# cd nginx
[root@sanchuang-linux nginx]# pwd
/var/log/nginx
[root@sanchuang-linux nginx]# ls
access.log  error.log							# 注:日志文件

六。练习:统计 web 服务器访问前十的用户#

统计 web 服务器访问前十的用户(注:通过 ip 判断)

#注:nginx查看访问次数最多的3个ip(笔试题常见)
#cat access.log |awk '{print $1}'|sort|uniq -c|sort -nr|head -3
[root@sanchuang-linux nginx]# head access.log 
192.168.0.42 - - [29/Oct/2020:12:01:01 +0800] "GET / HTTP/1.1" 200 4057 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3823.400 QQBrowser/10.7.4307.400" "-"
………………						# 注:awk命令 提取文本第一列数据 ip地址
[root@sanchuang-linux nginx]# cat access.log |awk '{print $1}'
192.168.0.42				# 注:默认以空格为分隔符,打印第一列$1
192.168.0.42
192.168.0.42
192.168.0.42
192.168.0.42
192.168.0.193
192.168.0.193
192.168.0.193
192.168.0.193				# 注:awk命令 提取文本第一列数据 ip地址
[root@sanchuang-linux nginx]# cat access.log |awk '{print $1}'|sort|uniq -c|sort -nr|head -3
      5 192.168.0.42		# 注:统计前3的访问量
      4 192.168.0.193

七. cut#

cut 命令

  • 从文本文件或者文本流中提取文本列
  • cut -选项 提取范围 文本文件

-----------------------------------

常见选项

  • -c:从指定提取范围中提取字符
  • -f:从指定提取范围中提取字段
  • -d:指定分隔符,默认分隔符为 tab 键

-----------------------------------

提取范围

n:第n项

n-:第n项到行尾

-m:行首到第m项

n,m:第n项和第m项

n-m:第n项到第m项

示例
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# w					# 注:w 当前用户登录情况
 14:45:33 up  4:12,  5 users,  load average: 0.00, 0.00, 0.03
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     tty1     -                三22   15:49   0.08s  0.08s -bash
root     pts/0    192.168.0.42     14:29    3.00s  0.02s  0.01s w
root     pts/1    192.168.0.42     14:29   15:35   0.00s  0.00s -bash
root     pts/3    192.168.0.42     09:48    4:56m  0.03s  0.03s -bash
root     pts/4    192.168.0.42     09:50    2:37m  0.52s  0.52s -bash
[root@sanchuang-linux ~]# who				# 注:w 看到更详细点
root     tty1         2020-10-28 22:15
root     pts/0        2020-10-29 14:29 (192.168.0.42)
root     pts/1        2020-10-29 14:29 (192.168.0.42)
root     pts/3        2020-10-29 09:48 (192.168.0.42)
root     pts/4        2020-10-29 09:50 (192.168.0.42)
方法1
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# w |tr -s " "|cut -d" " -f 1,2,4
 14:50:31 4:17,									# 注:默认分隔符为tab键,所有要压缩 
USER TTY LOGIN@									# 注:再指定分隔符为空格
root tty1 三22								   # 注:加tr -s " "
root pts/0 14:29
root pts/1 14:29
root pts/3 09:48
root pts/4 09:50
方法2
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# w |awk '{print $1,$2,$4}'		# 注:awk 默认分隔符是空白字符
14:51:28 up 5										    # 注:打印第1、2、4列
USER TTY LOGIN@
root tty1 三22
root pts/0 14:29
root pts/1 14:29
root pts/3 09:48
root pts/4 09:50

以冒号作为分隔符 截取用户名、用户 Id、用户属组#

以冒号作为分隔符 截取用户名、用户 Id、用户属组

写法1
[root@sanchuang-linux ~]# cat /etc/passwd|cut -d":" -f 1,3,5	
写法2(推荐)
[root@sanchuang-linux ~]# cut -d ":" -f 1,3,5 /etc/passwd	# 注:截取1,3,5列
#注:文本操作命令,可以直接操作文本,不需要用到cat

取值范围#

取值范围

[root@sanchuang-linux ~]# cut -d ":" -f 1,3,5 /etc/passwd	# 注:截取1,3,5列
[root@sanchuang-linux ~]# cut -d ":" -f 1-5 /etc/passwd		# 注:截取1-5列
[root@sanchuang-linux ~]# cut -d ":" -f 3- /etc/passwd		# 注:截取第3列--列尾
[root@sanchuang-linux ~]# cut -d ":" -f -3 /etc/passwd		# 注:截取前3列
============================================================================================
-c:从指定提取范围中提取字符
示例
[root@sanchuang-linux ~]# echo abcdefg |cut -c 2		# 注:截取第2个字符
b
[root@sanchuang-linux ~]# echo abcdefg |cut -c 2-5		# 注:截取2--5个字符
bcde
[root@sanchuang-linux ~]# echo abcdefg |cut -c 5-		# 注:截取第5到末尾字符
efg

八。练习#

练习

1统计access.log中排名前三的ip
2显示/boot目录下面所有的文件大小(包括子目录中的文件),并且由小到大排序
3统计/etc/passwd中每种shell使用的次数(降序排序)
4统计一下/etc/passwd中sbin这个单词出现了多少次
5只显示ens33的ip地址
============================================================================================
示例1:1统计access.log中排名前三的ip
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# cut -d "-" -f 1 access.log |sort|uniq -c|sort -nr|head -n3
      7 192.168.0.42 
      6 192.168.0.193 
      5 192.168.0.38 
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# cut -d " " -f1 access.log |sort|uniq -c
      6 192.168.0.193
      5 192.168.0.21
      5 192.168.0.32
      5 192.168.0.37
      5 192.168.0.38
      7 192.168.0.42
[root@sanchuang-linux ~]# cut -d " " -f1 access.log |sort|uniq -c|sort -nr
      7 192.168.0.42
      6 192.168.0.193
      5 192.168.0.38
      5 192.168.0.37
      5 192.168.0.32
      5 192.168.0.21
[root@sanchuang-linux ~]# cut -d " " -f1 access.log |sort|uniq -c|sort -nr|head -3
      7 192.168.0.42
      6 192.168.0.193
      5 192.168.0.38
============================================================================================
示例2:2显示/boot目录下面所有的文件大小(包括子目录中的文件),并且由小到大排序
方法1
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# du -ak /boot |sort -n  		# 注:以k为字节
4	/boot/.bashrc
4	/boot/efi/EFI/centos
4	/boot/grub2/device.map
4	/boot/grub2/grubenv
4	/boot/grub2/i386-pc/adler32.mod
4	/boot/grub2/i386-pc/all_video.mod
4	/boot/grub2/i386-pc/aout.mod

方法2
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# ll -R|grep root|tr -s " "|cut -d " " -f 5,9|sort -n
0 1214.txt
0 12244.txt
0 1224.txt
0 12456.txt
0 20
0 20
0 2020-09-24-18_25_03.txt

方法3
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# ll -R|grep root|awk '{print $5,$9}'|sort -n
0 1214.txt
0 12244.txt
0 1224.txt
0 12456.txt
0 20
0 20
0 2020-09-24-18_25_03.txt
0 abcd.txt
============================================================================================
示例3:3统计/etc/passwd中每种shell使用的次数(降序排序)
[root@sanchuang-linux ~]# cut -d : -f7 /etc/passwd |sort|uniq -c|sort -nr
     31 /bin/bash
     19 /sbin/nologin
      1 /sbin/shutdown
      1 /sbin/halt
      1 /bin/sync
============================================================================================
示例4:4统计一下/etc/passwd中sbin这个单词出现了多少次
方法1
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# grep -o sbin /etc/passwd
sbin
sbin
………………
sbin
sbin
[root@sanchuang-linux ~]# grep -o sbin /etc/passwd|wc -l
25

方法2
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# cat /etc/passwd|tr ":" "\n"|grep sbin|wc -l
25						# 注:将: 换成 换行符  同一行换到不同的行去
============================================================================================
示例5:5只显示ens33的ip地址
#ip a |grep ens33|grep inet|tr -s " "|cut -d " " -f3|cut -d"/" -f1
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# ip a |grep ens33
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    inet 192.168.0.34/24 brd 192.168.0.255 scope global dynamic noprefixroute ens33
[root@sanchuang-linux ~]# ip a |grep ens33|grep inet|tr -s " "|cut -d " " -f3
192.168.0.34/24
[root@sanchuang-linux ~]# ip a |grep ens33|grep inet|tr -s " "|cut -d " " -f3|cut -d"/" -f1
192.168.0.34

九. awk 指定分隔符 -F#

awk 指定分隔符 -F

[root@sanchuang-linux ~]# awk -F":" '{print $1}' /etc/passwd
root
bin
daemon
adm
lp
sync
…………………………

十. grep#

grep 命令

文本三剑客 ==> awk grep sed
https://www.cnblogs.com/end/archive/2012/02/21/2360965.html
grep 过滤 通用的正则表达式分析程序
grep、egrep、fgrep
做匹配来过滤的

用途:在文件中查找并显示包含指定字符串的行 格式:grep [选项]... 模式 目标文件

#注:模式 pattern --》模板

可以接受一个正则表达式

-i:查找时忽略大小写

-v:反转查找,输出与模式不相符的行

-n:显示符合模式要求的行号

-r:递归搜索所有文件

-o:只显示匹配的内容

-E:支持更多的元字符(支持扩展正则)

-A:找到匹配行以及后几行

-B:输出匹配行以及前几行

模式

^…. :以什么开头,整行以什么开头

…..$ :以什么结尾,整行以什么结尾

注:grep 是文本操作命令,可以直接操作文本

=====================================================================
示例1:-v:反转查找,输出与模式不相符的行
---------------------------------------------------------------------
[root@sanchuang-linux ~]# grep -v “#” /etc/yum.repos.d/centos.repo   
# 注:不输出包含# 的行
============================================================================================

示例2:-i 查找时忽略大小写
---------------------------------------------------------------------
[root@sanchuang-linux ~]# cd /etc/ssh/
[root@sanchuang-linux ssh]# pwd
/etc/ssh
[root@sanchuang-linux ssh]# grep -i "port" /etc/ssh/sshd_config 		# 注:查找时忽略大小写
# If you want to change the port on a SELinux system, you have to tell
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
#Port 22
# WARNING: 'UsePAM no' is not supported in Fedora and may cause several
#GatewayPorts no
============================================================================================

示例3:忽略大小写,并显示查找到的行号
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ssh]# grep -i -n "port" /etc/ssh/sshd_config 		# 注:显示符合模式要求的行号
13:# If you want to change the port on a SELinux system, you have to tell
15:# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
17:#Port 22
102:# WARNING: 'UsePAM no' is not supported in Fedora and may cause several
108:#GatewayPorts no
============================================================================================

示例4:-r 递归搜索所有文件
注:子目录以及子子目录下面查找
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ssh]# grep "xxxxx" * -r  				# 注:当前目录所有目录及子目录文件下的 递归查找
[root@sanchuang-linux ssh]# grep "GET" /var/log/nginx -r  	# 注:nginx目录下面 递归查找
/var/log/nginx/error.log:2020/10/29 12:01:02 [error] 12767#0: *2 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 192.168.0.42, server: _, request: "GET /favicon.ico HTTP/1.1", host: "192.168.0.34", referrer: "http://192.168.0.34/"
/var/log/nginx/error.log:2020/10/29 12:01:58 [error] 12767#0: *2 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 192.168.0.42, server: _, request: "GET /favicon.ico HTTP/1.1", host: "192.168.0.34"
--------------------------------------------------------------------------------------------
#递归查找/var/log/nginx下的所有文件(包括其下面子目录里的文件)
[root@mysql-binary nginx]# grep "GET" /var/log/nginx -r

十一。正则表达式#

正则表达式

^aa 表示以aa开头的行
aa$ 表示以aa结尾的行

[]      表示一个字符集
[a-z]   从a - z 中取一个
[^a-z]  不取a-z的字符
grep ^[^a-zA-Z0-9_] grep_test.txt  显示不以字母、数字、下划线开头的行
示例1:不输出以#开头的行
--------------------------------------------------------------------------------------------
[root@sanchuang-linux yum.repos.d]# grep -v ^# centos.repo
[root@sanchuang-linux yum.repos.d]# grep -v ^# centos.repo|grep -v ^$   # 注:不输出空白行
注:不输出空白行       grep -v ^$
   不输出以#开头的行  grep -v ^#
============================================================================================

示例2:过滤出grep_test.txt中,不以#号开头的行 非空白行
--------------------------------------------------------------------------------------------
[root@sanchuang-linux chenpeng]# cat grep_test.txt
#aaa
aaa#bbb

456
#
789
[root@sanchuang-linux chenpeng]# grep -v ^# grep_test.txt  # 注:过滤出不以#号开头的行
aaa#bbb

456
789

#方法1
[root@sanchuang-linux chenpeng]# grep -v ^# grep_test.txt |grep -v ^$	# 注:过滤出空白行
aaa#bbb                                      # 注:如果是空白字符  不会被过滤
456
789

#方法2
过滤出grep_test.txt中 不以#开头的行和非空白行
[root@sanchuang-linux chenpeng]# grep -v -E "^#|^$" grep_test.txt 
aaa#bbb                         # 注:-E 正则表达式 ,| 或者 , -v 不显示
456                             # 注:-E:支持更多的元字符(支持扩展正则)
789

十二. [] 表示一个字符集(正则表达式)#

[] 表示一个字符集(正则表达式)

[root@localhost chenpeng]# cat grep_test.txt 
abc
adc
Abdc
ac
a1c
axy
axc
123
777
示例1:过滤出abc adc
--------------------------------------------------------------------------------------------
[root@localhost chenpeng]# grep a[bd]c grep_test.txt        # 注:取字符集[bd]里面的其中1个
abc
adc
[root@sanchuang-linux chenpeng]# grep a[a-z]c grep_test.txt # 注:取出a-z中的1个字符
abc                                        # 注:ac    没有被过滤,必须有1个字符放在这里
adc                                        # 注:[a-z] 表示 从a - z 中取一个
axc
[root@sanchuang-linux chenpeng]# grep a[0-9]c grep_test.txt     # 注:取出0-9中的1歌字符
a1c
--------------------------------------------------------------------------------------------

示例2:[^a-z] 不取a-z的字符
--------------------------------------------------------------------------------------------
[root@sanchuang-linux chenpeng]# grep a[^a-z]c grep_test.txt    # 注:^取反,ac之间不取a-z的字符
a1c

示例3:取出不以字母开头的行
--------------------------------------------------------------------------------------------
[root@sanchuang-linux chenpeng]# grep ^[^a-zA-Z] grep_test.txt  # 注:不以a-zA-Z开头的行
11c
123                                   # 注:中间接空格  表示 包括空格
777
注:grep ^[a-zA-Z] grep_test.txt  以字母开头的行
============================================================================================
示例4:显示不以字母、数字、下划线开头的行
写法1
[root@sanchuang-linux chenpeng]# grep ^[^a-zA-Z0-9_] grep_test.txt
写法2
[root@sanchuang-linux chenpeng]# grep -v ^[a-zA-Z0-9_] grep_test.txt
#注:显示不以字母、数字、下划线开头的行

十三。通配符(正则表达式)#

通配符(正则表达式)

*     代表匹配前一个项任意次
?    代表匹配前一个项0次或者1次
+     代表匹配前一个项一次到多次
.     占位符 除\n之外的任意字符
{n,m} 匹配前一项n到m次
egrep 等同于 grep -E
fgrep 不支持任何正则,普通文本过滤
示例1:* ? + .
--------------------------------------------------------------------------------------------
#注:匹配的都是前面这个字符
[root@localhost ~]# cat grep_test.txt 
alc
axxc
ac
[root@localhost ~]# grep -E a.?c grep_test.txt    # 注:-E 支持更多正则扩展
alc                                               # 注:.  占位符(注=一定要有1个字符)
ac                                                # 注:.? 表示a和c之间.可以出现0次到1次
[root@localhost ~]# grep -E a.*c grep_test.txt    # 注:.* 表示a和c之间可以有任意个.(任意个字符)
alc               # 注:egrep 等同于 grep -E
axxc
ac
[root@localhost ~]# grep -E a.c grep_test.txt     # 注:.  表示a和c之间只有1个字符
alc
[root@localhost ~]# grep -E a.+c grep_test.txt    # 注:代表前一个字符.出现1个到多个
alc
axxc

示例2:{ }
--------------------------------------------------------------------------------------------
#注:匹配的都是前面这个字符
[root@localhost ~]# egrep "a.{1}c" grep_test.txt    # 注:指定 . 出现1次
alc
[root@localhost ~]# egrep "a.{1,2}c" grep_test.txt  # 注:指定 . 出现1次到2次
alc
axxc

示例3:{ }
--------------------------------------------------------------------------------------------
[root@localhost ~]# cat grep_test.txt 
alc
axxc
ac
ayy1c
addddddc
[root@localhost ~]# egrep "a.{1,5}c" grep_test.txt           # 注:前1项 . 出现1次到5次
alc
axxc
ayy1c

egrep 等同于 grep -E
fgrep  不支持正则,普通文本过滤

十四。练习:grep 正则表达式#

grep 正则表达式

1、进入 /lianxi 目录,复制 /etc/passwd 到当前目录下,然后对 passwd 进行操作

2、查找出当前 passwd 文件中以 ftp 或者 mail 开头的行,输出到屏幕

grep -E "^ftp|^mail" passwd
egrep "^ftp|^mail" passwd

3、查找出当前 passwd 文件中不以 r、m、f 开头的行

grep -v -E "^r|^m|^f" passwd
grep ^[^rmp] passwd

4、查找出当前 passwd 中以 bash 结尾的行

grep bash$ passwd

5、查找出 /etc/login.defs 文件中的有效行(不显示空行和注释行,以 #号开头的行)

grep -v -E "^#|^$" /etc/login.defs

6、查找出 /var/log/messages 文档中有 15 个字母的单词

grep -E "[^a-zA-Z][a-zA-Z{15}][^a-zA-Z]" /var/log/message  # 注:左右不是单词,中间15个字母
grep -E "\b[a-zA-Z{15}]\b" /var/log/message                # 注:\b自动匹配单词的边界

7、查找出 /etc/passwd 文件里用户名包含 liu 同时使用 bash 的用户

grep liu /etc/passwd|grep bash$|cut -d":" -f1

8、查找出 /etc/ssh/sshd_config 里的有效行

grep -v -E "^#|^$" /etc/ssh/sshd_config

9、查找出 /etc/ssh/sshd_config 文件里包含连续 2 个字符的行

grep -E "(.)\1" /etc/ssh/sshd_config 
grep -E "(.)\1"  # 注:.除了换行的任意一个字符  \1前面这个组在\1这里又出现一次(一模一样)  

10、查找出包含特殊字符的行

grep -E "[^0-Z]" grep_test.txt

11、查找出不包含数字的行

grep -v "[0-9]" abc.txt

12、查找出 /var/log/secure 里的 ip 地址

cut -d " " -f11 /var/log/secure|grep -E "\.."|sort|uniq    注:\.转义  第二个. 表示任1字符
--------------------------------------------------------------------------------------------
grep -E "((([0-9])|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))\.){3}(([0-9])|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))" ip_test.txt
============================================================================================
ip地址匹配:
   Ipv4  0-255  4个    192.168.1.0
注:匹配ip地址
[root@sanchuang-linux ~]# grep -E "((([0-9])|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))\.){3}(([0-9])|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))" ip_test.txt
192.168.0.1
192.168.1.255
172.0.0.1

((([0-9])|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))\.){3}(([0-9])|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))
#括号括起来表示一个组

分析
0-255
0-9                                     个位数
[1-9][0-9]                              十位数
(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5])   百位数

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.