您的位置:首页 > 运维架构 > Shell

shell入门-grep过滤-1

2015-11-17 20:30 393 查看
正则表达式,就是一个字符串。有一定的规律。我们用指定的字符串匹配一个指定的行。指定的字符串就是正则表达式。

正则表达式有这几个工具:grep egrep sed awk

命令:gerep

说明:过滤出指定的行

选项:--color 关键字有颜色

-n 显示行号

-c 显示一共出现了多少行

-v 取反 不包含指定字符的行

-A n n指数字 例如A2在有指定字符的行下面再显示两行

-B n n指数字 例如B2 在有指定字符的行上面再显示两行

-C n n指数字 例如C2 在有指定字符的行上面和下面再显示各两行

-r 显示目录里的所以带指定字符的行

-rh 显示目录里的所以带指定字符的行并不显示文件路径和文件名

grep 过滤出有root的行

[root@wangshaojun ~]# grep --color 'root' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

grep -n

[root@wangshaojun ~]# grep -n 'root' /etc/passwd
1:root:x:0:0:root:/root:/bin/bash
11:operator:x:11:0:operator:/root:/sbin/nologin

给grep创建个别名,把/etc/passwd拷贝一下

[root@wangshaojun ~]# vim .bashrc

alias cg=‘grep --color’

[root@wangshaojun ~]# cp /etc/passwd 1.txt
cp:是否覆盖"1.txt"? y

-c

[root@wangshaojun ~]# cg -c 'root' 1.txt
2

-v

[root@wangshaojun ~]# cg -v 'root' 1.txt
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

....

-A

[root@wangshaojun ~]# cg -n -A 2 'root' 1.txt
1:root:x:0:0:root:/root:/bin/bash
2-bin:x:1:1:bin:/bin:/sbin/nologin
3-daemon:x:2:2:daemon:/sbin:/sbin/nologin
--
11:operator:x:11:0:operator:/root:/sbin/nologin
12-games:x:12:100:games:/usr/games:/sbin/nologin
13-gopher:x:13:30:gopher:/var/gopher:/sbin/nologin

-B

[root@wangshaojun ~]# cg -n -B1 'root' 1.txt
1:root:x:0:0:root:/root:/bin/bash
--
10-uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
11:operator:x:11:0:operator:/root:/sbin/nologin

-C

[root@wangshaojun ~]# cg -n -C1 'root' 1.txt
1:root:x:0:0:root:/root:/bin/bash

2-bin:x:1:1:bin:/bin:/sbin/nologin
--
10-uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
11:operator:x:11:0:operator:/root:/sbin/nologin
12-games:x:12:100:games:/usr/games:/sbin/nologin

-r

[root@wangshaojun ~]# cg -r 'root' ~

.....

/root/.bash_history:HOME=/root
/root/.bash_history:grep 'root' /etc/passwd
/root/.bash_history:grep -n 'root' 1.txt
/root/.bash_history:grep -c 'root' 1.txt
/root/.bash_history:grep -v 'root' 1.txt
/root/.bash_history:grep -A2 'root' 1.txt
/root/.bash_history:grep -n -A2 'root' 1.txt
/root/.bash_history:grep -n -b2 'root' 1.txt
/root/.bash_history:grep 'root' /etc/passwd
/root/.bash_history:grep -n 'root' /etc/passwd
/root/.bash_history:cg -c 'root' 1.txt

.......

[root@wangshaojun ~]# cg -rh 'root' ~

....

HOME=/root
grep 'root' /etc/passwd
grep -n 'root' 1.txt
grep -c 'root' 1.txt
grep -v 'root' 1.txt
grep -A2 'root' 1.txt
grep -n -A2 'root' 1.txt
grep -n -b2 'root' 1.txt
grep 'root' /etc/passwd
grep -n 'root' /etc/passwd
cg -c 'root' 1.txt

......

//////////////////////////////////////////////////////////////////////////

总结:vim ~/.bashrc /// alias cg=‘grep --color’

cg -n -v -c -r -rh -An -Bn -Cn
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: