【Linux命令】grep

GREP命令:进行字符串数据的比对,并将符合指定模式的字符串行打印出来。

1.命令介绍

grep [-A] [-B] [-n] [-v] [--color=auto] '搜寻的关键字' filename

-A:后面可加数字,为after的意思,除了列出该行外,后续的n行也列出来;
-B: 后面可加数字,为before的意思,除了列出该行外,前面的n行也列出来;
–color=auto: 可将匹配到的关键字加颜色进行标注
-n:这个选项指示 grep 在输出的每一行前面显示行号。它可以帮助用户快速定位到匹配的内容。
-v:这个选项用于反向选择(invert match)匹配的行。也就是说,使用这个选项时,grep 将输出所有不匹配指定模式的行。
-i:这个选项表示“忽略大小写”。也就是说,在搜索字符串时,grep 将忽略字母的大小写。例如,the 会匹配 The、THE、tHe 等。

基础正则表达式

在这里插入图片描述

原始文档如下:

abcdefg
ABCDEFG
1234567890

0000000000
1111111111

TTTTTTTTTT


EFKLSPF;SAKD;F
goodbye

获取’00’所在的行的命令

grep -A5 -B4  -n '00' example.txt 

打印结果:
在这里插入图片描述

2.练习题:

原始文件:regular_express.txt,文件内容 共22行,最后一行为空白行

"Open Source" is a good mechanism to develop programs.
apple is my favorite food.
Football game is not use feet only.
this dress doesn't fit me.
However, this dress is about $ 3183 dollars.^M
GNU is free air not free beer.^M
Her hair is very beauty.^M
I can't finish the test.^M
Oh! The soup taste good.^M
motorcycle is cheap than car.
This window is clear.
the symbol '*' is represented as start.
Oh! My god!
The gd software is a library for drafting programs.^M
You are the best is mean you are the no. 1.
The world <Happy> is the same with "glad".
I like dog.
google is the best tools for search keyword.
goooooogle yes!
go! go! Let's go.
# I am VBird

2.1 练习(一):

2.1.1 读取加行号的文件内容:
cat -n regular_express.txt

读取结果:
在这里插入图片描述

2.1.2 查找特定字符串"the",并标准关键字所在的行号
 grep -n 'the' regular_express.txt 

搜索结果:
在这里插入图片描述

2.1.3 反向选择:查找不含字符串"the"的行

命令:

grep -vn 'the' regular_express.txt 

搜索结果:
在这里插入图片描述

2.1.4 取得不论大小的the

命令:

grep -in 'the' regular_express.txt

搜搜结果:
在这里插入图片描述

2.2 练习(二)

2.2.1 利用中括号[]来搜寻集合字符
grep -n 't[ae]st' regular_express.txt

搜索结果:
在这里插入图片描述

2.2.2 搜索以小写字母打头的行
 grep -n '^[a-z]' regular_express.txt

搜索结果:
在这里插入图片描述

2.2.3 搜索不是以字母打头的行

说明:

方式1:

grep -n '^[^[:alpha:]]' regular_express.txt  

方式2:

grep -n '^[^a-zA-Z]' regular_express.txt

搜索结果:
在这里插入图片描述

2.3 练习(三)

2.3.1 获取空白行
grep -n '^$' regular_express.txt

搜索结果:
在这里插入图片描述

2.3.2 获取至少两个o以上的字符串
grep -n 'ooo*' regular_express.txt 

说明:前面两个o必须要,最后一个o是可有可无的多个o
搜索结果:
在这里插入图片描述

2.3.3 获取g开头且g结尾的字符串
grep -n 'g.*g' regular_express.txt

搜索结果:

2.4 练习(四)

限定范围字符{}
找出含有2-5个o的字符串的命令

grep -n 'o\{2,5\}' regular_express.txt

搜索结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值