shell 正則表達式

部份內容參考以下連接
https://www.runoob.com/linux/linux-comm-sed.html?hmsr=toutiao.iohtml

一 、四種正則的用法.?+*

一、 . 匹配任意一個字符

表示點所在位置能夠表示任意一個字符,linux

咱們作一個測試文本正則表達式

cp /etc/passwd  test.txt

在test.txt 行首加一行raaoshell

sed -i '1i'\raao test.txt
grep  'r.o'  test.txt

shell 正則表達式
要想獲取raao 行,可使用
{n} 表示匹配前面字符n次
egrep 'r.{2}o' test.txt
shell 正則表達式ide

二、 ? 匹配以前的項0次或1次

編輯 test.txt 文件加入三行, rooot,rot,rt測試

sed -i '1i'\ rooot test.txt
sed -i '1i'\ rot test.txt
sed -i '1i'\ rt test.txt

egrep 'roo?t' test.txt
shell 正則表達式3d

三、+ 匹配以前的項一次或屢次

egrep 'ro+t' test.txt
shell 正則表達式code

四、* 匹配以前的項0次或屢次

egrep 'ro*t' test.txthtm

shell 正則表達式

二 、sed用法補充

sed 用法補充
動做說明:
a :新增, a 的後面能夠接字串,而這些字串會在新的一行出現(目前的下一行)~
c :取代, c 的後面能夠接字串,這些字串能夠取代 n1,n2 之間的行!
d :刪除,由於是刪除啊,因此 d 後面一般不接任何咚咚;
i :插入, i 的後面能夠接字串,而這些字串會在新的一行出現(目前的上一行);
p :打印,亦即將某個選擇的數據印出。一般 p 會與參數 sed -n 一塊兒運行~
s :取代,能夠直接進行取代的工做哩!一般這個 s 的動做能夠搭配正規表示法!例如 1,20s/old/new/g 就是啦!blog

一、打印:

打印第一行
sed -n 1p test.txt
打印前兩行
sed -n 1,2p test.txt
shell 正則表達式

二、刪除:

刪除前3行後打印10行
sed 1,3d test.txt |head
shell 正則表達式
查詢後刪除
sed '/root/d' test.txt |head
shell 正則表達式

三、插入:

能夠分爲a在當前行的下一行插入,i 在當前行的上一行插入
在文本開頭插入
sed '1i'\up test.txt
shell 正則表達式

在文本結尾插入
sed '$a'\down test.txt
shell 正則表達式

四、取代:

取代前4行內容爲replace1-4輸出
sed '1,4c replace1-4' test.txt
shell 正則表達式

五、替換:

作一個全局替換將nologin替換爲longout
sed 's/nologin/longout/g' test.txt
shell 正則表達式
數據查找並替換
ifconfig ens33 |grep '\binet\b' |sed 's/^.*inet//g' |sed 's/netmask.*$//g'
至關於
ifconfig ens33 |grep '\binet\b' |awk '{print $2}'
shell 正則表達式備註:grep' \b\b' \b單詞鎖定符,如: '\binet\b'只匹配inet,至關於-w 選項

相關文章
相關標籤/搜索