【Shell】数据过滤与正则表达式

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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ACHAI:)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值