Shell正则表达式学习笔记

2019-09-23 09:21:00于海丽

4. 示例

[root@localhost shell]# cat student.txt 
ID   Name  Gender Mark
1    ming  F    85
2    zhang  F    70
3    wang  M    75
4    li   M    90#测试-n参数
[root@localhost shell]# sed -n '2p' student.txt 
1    ming  F    85#测试单行删除
[root@localhost shell]# sed '2d' student.txt 
ID   Name  Gender Mark
2    zhang  F    70
3    wang  M    75
4    li   M    90#测试多行删除
[root@localhost shell]# sed '2,4d' student.txt 
ID   Name  Gender Mark
4    li   M    90#测试追加
[root@localhost shell]# sed '2a test append' student.txt
ID   Name  Gender Mark
1    ming  F    85
test append
2    zhang  F    70
3    wang  M    75
4    li   M    90#测试插入
[root@localhost shell]# sed '2i test insert' student.txt
ID   Name  Gender Mark
test insert
1    ming  F    85
2    zhang  F    70
3    wang  M    75
4    li   M    90#测试行替换
[root@localhost shell]# sed '2c test replace' student.txt
ID   Name  Gender Mark
test replace
2    zhang  F    70
3    wang  M    75
4    li   M    90#测试内容替换
[root@localhost shell]# sed '2s/ming/replace/g' student.txt
ID   Name  Gender Mark
1    replace F    85
2    zhang  F    70
3    wang  M    75
4    li   M    90

下面看看简单的正则表达式的匹配范例,通过这些范例,相信可以比较熟练的掌握基本的正则表达式的使用:

HelloWorld   匹配任意一行任何位置上的10个字母:HelloWorld
^HelloWorld  匹配出现在行首的10个字母:HelloWorld
HelloWorld$  匹配出现在行尾的10个字母:HelloWorld
^HelloWorld$  匹配只包括这10个字母:HelloWorld的一行
[Hh]elloWorld  匹配HelloWorld或者helloworld
Hello.World   匹配含有Hello这5个字母,再加上任何一个字符,再加上world
Hello*World  匹配含有Hello这5个字母,再加上任意个字母,再加上world

在上面的例子中利用“.”或者“*”,可以匹配0个或者多个字符,但是如果要匹配的字符是一个范围,这时候就要用到“{}”,因为shell中的 "{"和"}"有特殊含义,所以需要使用转移字符“”,例如:
[kouyang@kouyang  kouyang] #  grep -n 'o{2}'  hello.txt
在hello.txt文件中找出出现两个连续的"o"的那一行

[kouyang@kouyang kouyang]# grep  -n 'go{2, 5}g' hello.txt
在hello.txt文件中找到go后面出现2~5个"o"后面再紧接着一个"g"的单词的那一行