1.grep,egrep
1.grep用法
grep [匹配条件] [处理文件]
2.grep的参数
-i ##忽略字母大小写
-v ##条件取反
-c ##统计匹配行数
-q ##静默,无任何输出
-n ##显示匹配结果所在的行号
-q:
[root@server mnt]# grep '172.25.254.250' /etc/hosts && echo 'YES' || echo 'NO'
172.25.254.250 content.example.com
YES
[root@server mnt]# grep -q '172.25.254.250' /etc/hosts && echo 'YES' || echo 'NO'
YES
-c:
[root@server mnt]# egrep -c '/sbin/nologin' /etc/passwd
35
2.基本元字符
^ :
[root@foundation63 ~]# egrep '^root' /etc/passwd ##匹配以字符串 root 开头
root:x:0:0:root:/root:/bin/bash
$:
[root@foundation63 Desktop]# cat aaa
root sbin
root sbin root
root sbin sbin
[root@foundation63 Desktop]# egrep 'sbin$' aaa ##匹配以字符串 sbin 结尾
root sbin
root sbin sbin
. 过滤非空行:
[root@foundation63 Desktop]# egrep '.' aaa
过滤空行的两种方法
[root@foundation63 Desktop]# egrep -v '.' aaa
[root@foundation63 Desktop]# egrep '^$' aaa
基本元字符: + ? *
[root@foundation63 Desktop]# egrep 'f+' 1.sh ##输出包括f,ff,fff....,即至少出现一次
colorful,color
colorfulful?
stuf
stuff
stufff
stuffff
stufawd
we adw dfg awda
wea web wef
[root@foundation63 Desktop]# egrep 'color(ful)?' 1.sh ##末尾的ful最多出现一次,也可以
colorful,color
colorfulful?
元字符:{}
[root@server ~]# egrep '(we){3}' 1.sh
rere wewewe
westos wewewewe Shell
[root@server ~]#
[root@server ~]#
[root@server ~]# egrep '(we){2,4}' 1.sh
xcvb wewe asdawd
rere wewewe
westos wewewewe Shell
[root@server ~]#
[root@server ~]# egrep '(we){3,}' 1.sh
rere wewewe
westos wewewewe Shell
[root@server ~]# egrep '(we)[ab]' 1.sh
weawe IPADDR
wea web wef
[root@server ~]# egrep '[A-Z]' 1.sh
weawe IPADDR
westos wewewewe Shell
3.cut命令
cut -d ##指定分隔符
cut -d : -f 1-3 /etc/passwd ##指定分隔符为:,显示第1到3列
cut -c 1,4 /etc/passwd ##显示第一和第四个字符
练习:获取主机IP
ifconfig eth0 | grep "inet " | awk '{print $2}'
ifconfig eth0 | grep "inet " | cut -d " " -f 10
练习:检测网络
ping -c1 -w1 172.25.254.$1 &> /dev/null && echo 172.25.254.$1 is up || echo 172.25.254.$1 is down