1、 显示/etc/rc.d/rc.sysinit文件中以不区分大小的h开头的行;
[root@openEuler ~]# grep -E "^(H|h)" /etc/passwd
halt:x:7:0:halt:/sbin:/sbin/halt
注:当然也可以使用grep -i来实现,这里我换了一个文件(/etc/passwd)
2、 显示/etc/passwd中以sh结尾的行;
[root@openEuler ~]# grep -E "sh$" /etc/passwd
root:x:0:0:Super User:/root:/bin/bash
openeuler:x:1000:1000:openEuler:/home/openeuler:/bin/bash
test02:x:1004:1004::/home/test02:/bin/bash
test03:x:1005:1005::/home/test03:/bin/bash
test04:x:1006:1006::/home/test04:/bin/bash
test05:x:1007:1007::/home/test05:/bin/bash
3、 显示/etc/fstab中以#开头,且后面跟一个或多个空白字符,而后又跟了任意非空白字符的行;
[root@openEuler ~]# grep -E "^#[[:space:]]+[^[:space:]]*" /etc/fstab
# /etc/fstab
# Created by anaconda on Sat Mar 16 12:06:55 2024
# Accessible filesystems, by reference, are maintained under '/dev/disk/'.
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info.
# After editing this file, run 'systemctl daemon-reload' to update systemd
# units generated from this file.
4、 查找/etc/rc.d/rc.local中包含“以to开始并以to结尾”的字串行;
[root@openEuler ~]# grep -E "^to.*to$" /etc/rc.d/rc.local
[root@openEuler ~]#
5、 查找/etc/inittab中含有“以s开头,并以d结尾的单词”模式的行;
[root@openEuler ~]# grep -Ew "s[[:alpha:]]+d" /etc/inittab
# Ctrl-Alt-Delete is handled by /usr/lib/systemd/system/ctrl-alt-del.target
# systemd uses 'targets' instead of runlevels. By default, there are two main targets:
效果如下:
6、 查找ifconfig命令结果中的1-255之间的整数;
[root@openEuler ~]# ifconfig | grep -Ew "[1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-5][0-5]" inet 192.168.54.150 netmask 255.255.255.0 broadcast 192.168.54.255inet6 fe80::20c:29ff:fe95:6d47 prefixlen 64 scopeid 0x20<link>ether 00:0c:29:95:6d:47 txqueuelen 1000 (Ethernet)RX packets 4383 bytes 384873 (375.8 KiB)
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536inet 127.0.0.1 netmask 255.0.0.0inet6 ::1 prefixlen 128 scopeid 0x10<host>inet 192.168.122.1 netmask 255.255.255.0 broadcast 192.168.122.255ether 52:54:00:ed:da:6c txqueuelen 1000 (Ethernet)
效果如下:
7、 显示/var/log/secure文件中包含“Failed”或“FAILED”的行;
[root@openEuler ~]# grep -E "(Failed|FAILED)" /var/log/secure
grep: /var/log/secure: binary file matches
注:这里意味着 /var/log/secure
被识别为二进制文件。grep
主要用于处理文本文件,在二进制文件上使用可能会导致不期望的结果或错误。代码应该是没有错的,换一个文件,或者自己创建一个文件练习就可以了。
8、 在/etc/passwd中取出默认shell为bash的行;
[root@openEuler ~]# grep -E "bash$" /etc/passwd
root:x:0:0:Super User:/root:/bin/bash
openeuler:x:1000:1000:openEuler:/home/openeuler:/bin/bash
test02:x:1004:1004::/home/test02:/bin/bash
test03:x:1005:1005::/home/test03:/bin/bash
9、 以长格式列出/etc/目录下以ns开头、.conf结尾的文件信息;
[root@openEuler ~]# ll /etc/ns*.conf
-rw-r--r--. 1 root root 1516 Mar 16 20:08 /etc/nsswitch.conf
10、高亮显示passwd文件中冒号,及其两侧的字符;
[root@openEuler ~]# grep -E "(:|[^[:space:]]:[^[:space:]])" /etc/passwd
root:x:0:0:Super User:/root:/bin/bash
bin:x:1:1:bin:/bin:/usr/sbin/nologin
daemon:x:2:2:daemon:/sbin:/usr/sbin/nologin
adm:x:3:4:adm:/var/adm:/usr/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/usr/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
效果如下: