文章目录
- 二、进阶部分:
- 1.1 只在目录中所有的.php和.html文件中递归搜索字符"main{}"
- 1.2 在搜索结果中排除所有README文件
- 1.3 在搜索结果中排除filelist文件列表里的文件
- 1.4 在多级目录中对文本进行递归搜索
- 1.5 搜索多个文件并查找匹配文本在哪些文件中
- 1.6 搜索fstab开头不是英文字母的行,并显示行号
- 1.7 搜索fstab中c后面跟1,2个d,后面再跟一个3的字符串的行
- 1.8 过滤空行和开始为#开始的行
- 1.9 找出/etc/rc.d/rc.sysinit或/etc/grub.conf文件中,以至少一个空白字符开头,且后面存在非空白字符的行
- 1.10 列出系统所有系统用户
- 1.11 过滤functions文件中,以单词或者单词前面跟了一个"_"开头的行,并显示前后2行
二、进阶部分:
1.1 只在目录中所有的.php和.html文件中递归搜索字符"main{}"
[root@localhost ~]# grep "main{}" . -r --include=*.{php,html}
1.2 在搜索结果中排除所有README文件
[root@localhost ~]# grep "main{}" /tmp -r --exclude "README"
1.3 在搜索结果中排除filelist文件列表里的文件
[root@localhost ~]# grep "main{}" . -r --exclude-from filelist
filelist文件中有的文件名
1.4 在多级目录中对文本进行递归搜索
[root@localhost ~]# grep "test" /tmp -r -n
1.5 搜索多个文件并查找匹配文本在哪些文件中
[root@localhost ~]# grep -l "a" test1 test2
1.6 搜索fstab开头不是英文字母的行,并显示行号
[root@localhost ~]# grep -n -E '^[^a-zA-Z]' /etc/fstab
1.7 搜索fstab中c后面跟1,2个d,后面再跟一个3的字符串的行
[root@localhost ~]# grep -n -E 'cd{1,2}3' /etc/fstab
1.8 过滤空行和开始为#开始的行
[root@localhost ~]# grep -Evn '^#|^$' /etc/fstab
1.9 找出/etc/rc.d/rc.sysinit或/etc/grub.conf文件中,以至少一个空白字符开头,且后面存在非空白字符的行
[root@localhost ~]# grep -P '^\s+\S' /etc/rc.d/rc.sysinit /etc/grub.conf
7里没有rc.stsinit、grub.conf
[root@localhost ~]# grep -P '^\s\S+'
1.10 列出系统所有系统用户
[root@localhost ~]# cat /etc/passwd | grep -P '\b[1-9]\d{0,2}\b'
[root@localhost ~]# cat /etc/passwd | cut -d: -f3 | sort -n | grep -P '\b[1-9]\d{0,2}\b'
[root@localhost ~]# cat /etc/passwd | cut -d: -f3 | sort -n | grep -E '\<([1-9]|[1-9][0-9]{0,2})\>'
用awk方法
[root@localhost ~]# cat /etc/passwd | awk -F: '$>1 && $3<1000{print $0}'
1.11 过滤functions文件中,以单词或者单词前面跟了一个"_"开头的行,并显示前后2行
[root@localhost ~]# grep -P -C 2 '^_?\b\w+\b' /etc/rc.d/init.d/functions
[root@localhost ~]# grep -P -C 2 '^_{0,1}\b\w+\b' /etc/rc.d/init.d/functions