三剑客-grep

grep常用用法

-w  按照单词匹配 空格特殊符号 \<\>等同于-w

[root@m01 ~]# grep -w oldboy oldboy.txt
I am oldboy teacher

[root@m01 ~]# grep '\<oldboy\>' oldboy.txt
I am oldboy teacher

找出某个关键词的左边或右边的东西
零宽断言 (perl正则)

[root@web03 ~]# echo byoldboylinux |grep -Po '(?<=oldboy)linux'
linux

[root@web03 ~]# echo byoldboylinux |grep -Po 'by(?=oldboy)'
by

[root@www ~]# grep [-acinv] [--color=auto] '搜寻字符串' filename
选项与参数:
-a :将 binary 文件以 text 文件的方式搜寻数据
-c :计算找到 '搜寻字符串' 的次数
-i :忽略大小写的不同,所以大小写视为相同
-n :顺便输出行号
-v :反向选择,亦即显示出没有 '搜寻字符串' 内容的那一行!
--color=auto :可以将找到的关键词部分加上颜色的显示喔!

将/etc/passwd,有出现 root 的行取出来
# grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
或
# cat /etc/passwd | grep root 
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
将/etc/passwd,有出现 root 的行取出来,同时显示这些行在/etc/passwd的行号
# grep -n root /etc/passwd
1:root:x:0:0:root:/root:/bin/bash
30:operator:x:11:0:operator:/root:/sbin/nologin
将/etc/passwd,将没有出现 root 的行取出来
# grep -v root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
将/etc/passwd,将没有出现 root 和nologin的行取出来
# grep -v root /etc/passwd | grep -v nologin
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
行首与行尾字节 ^ $
行首字符:如果我想要让 the 只在行首列出呢? 这个时候就得要使用定位字节了!我们可以这样做:

[root@www ~]# grep -n '^the' regular_express.txt
12:the symbol '*' is represented as start.
如果我不想要开头是英文字母,则可以是这样:
[root@www ~]# grep -n '^[^a-zA-Z]' 
regular_express.txt 1:"Open Source" is a good mechanism to develop programs. 21:# I am VBird
那如果我想要找出来,行尾结束为小数点 (.) 的那一行:
[root@www ~]# grep -n '\.$' regular_express.txt
1:"Open Source" is a good mechanism to develop programs.
2:apple is my favorite food.
3:Football game is not use feet only.
特别注意到,因为小数点具有其他意义(底下会介绍),所以必须要使用转义字符(\)来加以解除其特殊意义!
找出空白行:
[root@www ~]# grep -n '^$' regular_express.txt
22:

猜你喜欢

转载自www.cnblogs.com/fangdecheng/p/9960200.html