1.7数据过滤与正则表达式
grep命令
grep可以查找关键词并打印匹配的行——过滤作用
用法:grep 【选项】 匹配模式 【文件】
-i :忽略字母大小写
-v :取反匹配
-w :匹配单词
-q :静默匹配,不显示匹配结果
[root@localhost ~]# grep IPADDR /etc/sysconfig/network-scripts/ifcfg-ens32
IPADDR=172.16.10.10
Everything is a file
1)基本正则表达式
复制模板文件
[root@localhost ~]# cp /etc/passwd /tmp/
查找包含root的行(不是匹配字段)
[root@localhost ~]# grep "root" /tmp/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
cj:x:1000:1000:root:/home/cj:/bin/bash
查找与”0:“之间包含任意两个字符的字符串,并显示该行
[root@localhost ~]# grep "..0:" /tmp/passwd
root:x:0:0:root:/root:/bin/bash
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
查找包含至少一个0的行(第一个0必须出现,第二0可以出现0次或n次)
[root@localhost ~]# grep "00*" /tmp/passwd
root:x:0:0:root:/root:/bin/bash
sync:x:5:0:sync:/sbin:/bin/sync
cj:x:1000:1000:root:/home/cj:/bin/bash
mfs:x:1001:1001::/home/mfs:/sbin/nologin
查找以root开头的行
[root@localhost ~]# grep "^root" /tmp/passwd
root:x:0:0:root:/root:/bin/bash
查找以bash结尾的行
[root@localhost ~]# grep "bash$" /tmp/passwd
root:x:0:0:root:/root:/bin/bash
cj:x:1000:1000:root:/home/cj:/bin/bash
2)扩展正则表达式
查找存在root或者bash存在的行
[root@localhost ~]# egrep "(root|bash)" /tmp/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
cj:x:1000:1000:root:/home/cj:/bin/bash
查找包含至少一个0的行
[root@localhost ~]# egrep "0+" /tmp/passwd
root:x:0:0:root:/root:/bin/bash
sync:x:5:0:sync:/sbin:/bin/sync
1.8算术运算
#!/bin/bash
read -p "输入数字:" num
sum=$[num*(num+1)/2]
echo "正确答案为$sum"
[root@localhost ~]# ./jisuan.sh
输入数字:12
正确答案为78