正则表达式

一、正则特殊符号:

1、;作用:命令的分隔符,前面的命令失败或者正确都会继续执行

案例1:命令的拼接
[root@web01 ~]# ll;mkdir web;cd web;pwd
total 4
-rw-r--r-- 1 root root 1000 Nov 23 22:57 test.zip
/root/web

案例2:命令执行错误不影响后续命令执行
[root@web01 ~]# lll;mkdir web;cd web;pwd
-bash: lll: command not found
/root/web

2、&&作用:命令分隔符,前面的命令必须成功才会执行&&后面的命令

案例1:执行正确的命令
[root@web01 ~]# mkdir web && cd /tmp
[root@web01 tmp]# pwd
/tmp

案例2:命令执行错误
[root@web01 ~]# ping -w1 -c1 www.baiduuuu.com && cd /tmp
ping: www.baiduuuu.com: Name or service not known
[root@web01 ~]# ping -w1 -c1 www.baiduuuu.com
ping: www.baiduuuu.com: Name or service not known
[root@web01 ~]# echo $?
2

3、||作用:前面的必须执行失败,才执行||后面的命令

案例1:执行成功的命令
[root@web01 ~]# mkdir web || cd web
[root@web01 ~]# ll
total 4
drwxr-xr-x 2 root root    6 Nov 26 20:21 web

案例2:执行错误的命令
[root@web01 ~]# cd web || mkdir web
-bash: cd: web: No such file or directory
[root@web01 ~]# ll
total 4
drwxr-xr-x 2 root root    6 Nov 26 20:26 web
[root@wen01 ~]# cd oldboy || mkdir -p web || ls web
[root@web01 web]# ls							不执行
1.txt

案例3:一起使用注意,判断紧挨着前面的命令执行结果
[root@web01 ~]# ping -w1 -c1 www.baiduaaaaa.com &> /dev/null && echo ok || echo error
error

二、正则表达式

1、概念:

  1. 正则表达式是为了处理大量文件/文本/字符串而定义的一套规律和方法
  2. 通过定义的这些特殊符号的辅助,系统管理员可以快速过滤,替换或输出需要的字符串
  3. Linux正则表达式一般以行为单位处理

2、常用符号:

2.1、 ^

^word :找以word开头的行		# ^以……开头的行
[root@web01 ~]# grep '^o' web.txt
our site is http:www.lizhenya.com

# -v:表示除去“#”的其他打印出来
[root@wen01 ~]# grep -v '#' /etc/selinux/config
SELINUX=disabled
SELINUXTYPE=targeted

# -i:表示不区分大小写
[root@web01 ~]# grep -i '^i' web.txt
I am lizhenya teacher!
I teach linux.
I like badminton ball ,billiard ball and chinese chess!

2.2、$

# 环境准备
[root@web01 ~]# cat web.txt
I am lizhenya teacher!
I teach linux.
test

I like badminton ball ,billiard ball and chinese chess!
my blog is http: blog.51cto.com 
our site is http:www.lizhenya.com 
my qq num is 593528156

aaaa,
not 572891888887.
^^^^^^^^66$$$$$$$^^^$$
lizhenyalizhenyalizhenya


m$:查找以文件内以m结尾的行;注意:必须以……结尾,包括空格
[root@web01 ~]# grep 't$' web.txt 		# 以t结尾
test
[root@web01 ~]# grep '^$' web.txt 		# 以空格开头空格结尾

[root@web01 ~]# grep 'm$' web.txt 		# 没有显示答案是因为后面有个空格
[root@web01 ~]# grep 'm $' wen.txt
my blog is http: blog.51cto.com
our site is http:www.lizhenya.com

[root@web01 ~]# grep -v '^#' /etc/selinux/config | grep -v '^$'
SELINUX=disabled
SELINUXTYPE=targeted

2.3、使用cat -A在文件的末尾显示\(;-A在文件末尾显示\)把tab键显示为^|

[root@web01 ~]# cat -A wen.txt
I am lizhenya teacher!$
I teach linux.$
test$
$
I like badminton ball ,billiard ball and chinese chess!$
my blog is http: blog.51cto.com $
our site is http:www.lizhenya.com $
my qq num is 593528156$
$
aaaa,$
not 572891888887.$
^^^^^^^^66$$$$$$$^^^$$$
lizhenyalizhenyalizhenya$

2.4、如果需要查$,则使用\还原本意

[root@web01 ~]# grep '\$' web.txt
^^^^^^^^66$$$$$$$^^^$$
posted @ 2024-08-17 19:45  Dusk_Yun  阅读(18)  评论(0)    收藏  举报