shell文本处理1:grep与cut命令

1.grep,egrep

1.grep用法

grep [匹配条件] [处理文件]

2.grep的参数

        -i	##忽略字母大小写
	-v	##条件取反
	-c	##统计匹配行数
	-q	##静默,无任何输出
	-n	##显示匹配结果所在的行号

-q:

[[email protected] mnt]# grep '172.25.254.250' /etc/hosts && echo 'YES' || echo 'NO'
172.25.254.250 content.example.com
YES
[[email protected] mnt]# grep -q '172.25.254.250' /etc/hosts && echo 'YES' || echo 'NO'
YES

-c:

[[email protected] mnt]# egrep -c '/sbin/nologin' /etc/passwd
35

2.基本元字符

^ :

[[email protected] ~]# egrep '^root' /etc/passwd     ##匹配以字符串 root 开头
root:x:0:0:root:/root:/bin/bash

shell文本处理1:grep与cut命令

$:

[[email protected] Desktop]# cat aaa

root sbin
root sbin root
root sbin sbin
[[email protected] Desktop]#  egrep 'sbin$' aaa      ##匹配以字符串 sbin 结尾
root sbin
root sbin sbin

shell文本处理1:grep与cut命令

. 过滤非空行:

[[email protected] Desktop]# egrep '.' aaa

shell文本处理1:grep与cut命令

过滤空行的两种方法

[[email protected] Desktop]#  egrep -v '.' aaa

[[email protected] Desktop]# egrep  '^$' aaa

shell文本处理1:grep与cut命令

基本元字符: + ? *

[[email protected] Desktop]# egrep 'f+' 1.sh 	##输出包括f,ff,fff....,即至少出现一次
colorful,color
colorfulful?
stuf
stuff
stufff
stuffff
stufawd
we adw dfg awda
wea web wef

[[email protected] Desktop]# egrep 'color(ful)?' 1.sh 	##末尾的ful最多出现一次,也可以
colorful,color
 colorfulful?

shell文本处理1:grep与cut命令

元字符:{}

[[email protected] ~]# egrep '(we){3}' 1.sh 
rere wewewe
westos wewewewe Shell
[[email protected] ~]# 
[[email protected] ~]# 
[[email protected] ~]# egrep '(we){2,4}' 1.sh 
xcvb wewe asdawd
rere wewewe
westos wewewewe Shell
[[email protected] ~]# 
[[email protected] ~]# egrep '(we){3,}' 1.sh 
rere wewewe
westos wewewewe Shell
[[email protected] ~]# egrep '(we)[ab]' 1.sh 
weawe IPADDR
wea web wef
[[email protected] ~]# 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