SHELL脚本学习(十一)正则表达式

一、锚点字符
1.1 锚点行首

脱字符(^)指出行首位置

shell 复制代码
$ cat < file1
test line1
test line2
test line3
line4 test

#打印所有包括文本 test的行
$ sed -n '/test/p' file1
test line1
test line2
test line3
line4 test

#打印所有以test为首的行
$ sed -n '/^test/p' file1
test line1
test line2
test line3
1.2 锚点行尾

美元符号($)指出行尾位置

shell 复制代码
$ cat < file1
test line1
test line2
test line3
line4 test

#打印所有以test结尾的行
$ sed -n '/test$/p' file1
line4 test
二、点字符

点字符(.)能够匹配除换行符之外的所有字符。

shell 复制代码
$ cat<file
cat
hat
 at
a t

$ sed -n '/.at/p' file
cat
hat
 at

空格也是一个字符

三、字符组

方括号 [] 用于定义字符组,字符组内的任一字符匹配,即为匹配。

shell 复制代码
$ cat<file
cat
hat
 at
a t
ubuntu@VM-8-14-ubuntu:~$ sed -n '/[ch]at/p' file
cat
hat
四、排除型字符组

在字符组前加上脱字符即为排除型字符组。排除型字符组的语义正好和字符组相反,不匹配字符组内的任一字符。

shell 复制代码
$ cat<file
cat
hat
 at
a t

$ sed -n '/[^ch]at/p' file
 at
五、区间

可以单连字符(-)表示区间。即 起始字符-结束字符。

shell 复制代码
$ sed -n '/[A-Z][Aa][Tt]/p' file
HAT
CAT

$ sed -n '/[a-z][Aa][Tt]/p' file
cat
hat

A-Z 表示 当前字符 要匹配单个 大写字母

a-z 表示 当前字符 要匹配单个 小写字母

六、特殊字符

除了定义自己的字符组,BRE(basic regular expression 基础正则表达式)还提供了一些特殊字符组。
BRE特殊字符组

字符组 描述
[[ :alpha:]] 匹配任意字符字符,a-z A-Z
[[:alnum:]] 匹配任意字母数字,z-a A-Z 0-9
[[:blank:]] 匹配空格或制表符
[[:digit:]] 匹配0-9中的数字
[[:lower:]] 匹配小写字母 a-z
[[:print:]] 匹配任意可打印字符
[[:punct:]] 匹配标点符号
[[:space:]] 匹配任意空白符。空格、制表符、换行符、回车等。。。
[[:upper:]] 匹配任意大写字母 A-Z

特殊字符组的使用方式和普通字符组一样。

shell 复制代码
$ cat <file
cat
hat
 at
a t
HAT
CAT

$ sed -n '/[[:upper:]][Aa][Tt]/p' file
HAT
CAT

$ sed -n '/[[:lower:]][Aa][Tt]/p' file
cat
hat
七、星号 *

在字符后面加 星号*,表示该字符必须匹配0次或多次。

shell 复制代码
$ echo "hello" | sed -n '/hel*o/p'
hello
$ echo "heo" | sed -n '/hel*o/p'
heo
$ echo "heto" | sed -n '/hel*o/p'
$ 
相关推荐
树℡独11 小时前
ns-3仿真之应用层(五)
服务器·网络·tcp/ip·ns3
小小管写大大码12 小时前
如何让vscode变得更智能?vscode接入claude实现自动编程
运维·ide·vscode·自动化·编辑器·ai编程·腾讯云ai代码助手
嵩山小老虎12 小时前
Windows 10/11 安装 WSL2 并配置 VSCode 开发环境(C 语言 / Linux API 适用)
linux·windows·vscode
Fleshy数模12 小时前
CentOS7 安装配置 MySQL5.7 完整教程(本地虚拟机学习版)
linux·mysql·centos
zhang1338308907512 小时前
CG-09H 超声波风速风向传感器 加热型 ABS材质 重量轻 没有机械部件
大数据·运维·网络·人工智能·自动化
a413244712 小时前
ubuntu 25 安装vllm
linux·服务器·ubuntu·vllm
Configure-Handler12 小时前
buildroot System configuration
java·服务器·数据库
津津有味道12 小时前
易语言TCP服务端接收刷卡数据并向客户端读卡器发送指令
服务器·网络协议·tcp·易语言
Fᴏʀ ʏ꯭ᴏ꯭ᴜ꯭.13 小时前
Keepalived VIP迁移邮件告警配置指南
运维·服务器·笔记