3.1.3 锚定匹配
学习目标
这一节,我们从 基础知识、简单实践、小结 三个方面来学习
基础知识
简介
所谓的锚定匹配,主要是在字符匹配的前提下,增加了字符位置的匹配
常见符号
^ 行首锚定, 用于模式的最左侧
$ 行尾锚定,用于模式的最右侧
^PATTERN$ 用于模式匹配整行
^$ 空行
^[[:space:]]*$ 空白行
\< 或 \b 词首锚定,用于单词模式的左侧
\> 或 \b 词尾锚定,用于单词模式的右侧
\<PATTERN\> 匹配整个单词
注意:
单词是由字母,数字,下划线组成
简单实践
准备实践文件
[root@localhost ~]# cat nginx.conf
#user nobody;
worker_processes 1;
http {
sendfile on;
keepalive_timeout 65;
server {
listen 8000;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
}
}
实践1-行首位地址匹配
行首位置匹配
[root@localhost ~]# grep '^wor' nginx.conf
worker_processes 1;
行尾位置匹配
[root@localhost ~]# grep 'st;$' nginx.conf
server_name localhost;
实践2-关键字匹配
关键字符串匹配
[root@localhost ~]# grep '^http {$' nginx.conf
http {
[root@localhost ~]# grep '^w.*;$' nginx.conf
worker_processes 1;
实践3-空行匹配
空行匹配
[root@localhost ~]# grep '^$' nginx.conf
[root@localhost ~]# grep '^[[:space:]]*$' nginx.conf
# 反向过滤空行
[root@localhost ~]# grep -v '^$' nginx.conf
#user nobody;
worker_processes 1;
http {
sendfile on;
keepalive_timeout 65;
server {
listen 8000;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
}
}
实践4-单词匹配
单词首部匹配
[root@localhost ~]# grep '\bloca' nginx.conf
server_name localhost;
location / {
[root@localhost ~]# grep '\<loca' nginx.conf
server_name localhost;
location / {
单词尾部匹配
[root@localhost ~]# grep 'ion\>' nginx.conf
location / {
[root@localhost ~]# grep 'ion\b' nginx.conf
location / {
单词内容匹配
[root@localhost ~]# grep '\<index\>' nginx.conf
index index.html index.htm;
[root@localhost ~]# grep '\<sendfile\>' nginx.conf
sendfile on;