Linux命令中的正则表达式
【注意】最后更新于 August 4, 2021,文中内容可能已过时,请谨慎使用。
在Linux命令行中,有许多场景会应用到正则表达式:
- apt-cache
- grep
- find
笔者在本文中收集一些具体的应用场景
apt-cache
笔者常常使用 ping 命令。但记不住安装包的全名,只记得以 -ping 结尾
我们可以使用表达式 .*-ping$ 查询安装包全名
root@ubuntu:/# apt-cache search '.*-ping$'
iputils-ping - Tools to test the reachability of network hosts
inetutils-ping - ICMP echo tool
grep
当我们查看 ip 地址的时候,只想获取地址数据:
root@ubuntu:/# ip address | grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
127.0.0.1
172.17.0.2
172.17.255.255
find
使用 -name 参数
root@ubuntu:~# find . -name '*.c' -print
./4321b.c
./2234.c
使用 -regex 参数
root@ubuntu:~# find . -regextype sed -regex '.*/[0-9]*\.c' -print
./2234.c
使用 -regex 时有要注意:-regex不是匹配文件名,而是匹配完整的文件名(包括路径)。