一.grep与egrep
1.grep定义
- Global search regular expression and print out the line
- grep命令是一种强大的文本搜索工具,根据用户指定的模式对目标文本进行批匹配检查,打印匹配到的行
- 由正则表达式或者字符及基本文本字符所编写的过滤条件
2.grep用法
grep [匹配条件] [处理文件]
3.grep的常用参数
-i ##忽略字母大小写
-v ##条件取反
-c ##统计匹配行数
-q ##静默,无任何输出
-n ##显示匹配结果所在的行号
-
-q: ##静默,无任何输出
[root@localhost mnt]# grep '172.25.254.254' /etc/hosts && echo 'YES' || echo 'NO' 172.25.254.254 classroom.example.com 172.25.254.254 content.example.com YES [root@localhost mnt]# grep -q '172.25.254.254' /etc/hosts && echo 'YES' || echo 'NO' YES
二.cut命令
cut -d ##指定分隔符
cut -d : -f 1-3 /etc/passwd ##指定分隔符为:,显示第1到3列
cut -c 1,4 /etc/passwd ##显示第一和第四个字符
三.练习
- 获取主机ip
[root@localhost mnt]# ifconfig eth0 | grep "netmask" | awk '{print $2}'
172.25.254.162
[root@localhost mnt]# ifconfig eth0 | grep "netmask" | cut -d " " -f 10
172.25.254.162
- 检测网络
[root@localhost mnt]# vim ping.sh
[root@localhost mnt]# cat ping.sh
#!/bin/bash
ping -c1 -w1 172.25.254.$1 &> /dev/null && echo 172.25.254.$1 is up || echo 172.25.254.$1 is down ##-c1表示ping的过程为一秒 -w1表示一次
[root@localhost mnt]# sh ping.sh 62
172.25.254.62 is up