Shell文本處理三劍客之sed的使用
更新時間:2020年10月16日 10:01:25 作者:whoru
這篇文章主要介紹了Shell文本處理三劍客之sed的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
sed 是 stream editor 的縮寫,流編輯器,主要用于對標準輸出或文件進行處理。
語法:
stdout | sed [option] "pattern command" sed [option] "pattern command" file1
常用選項(option)
# -n 只打印靜默模式匹配行,而不輸出原行 # p 是打印命令 ➜ sed '/hello/p' helloWorld.sh #!/bin/bash HELLO bash echo "hello world" echo "hello world" ➜ sed -n '/hello/p' helloWorld.sh echo "hello world" # -e 追加一組編輯命令 ➜ sed -n -e '/hello/p' -e '/HELLO/p' helloWorld.sh HELLO bash echo "hello world" # -f 把所有編輯命令保存在文件中,適用于復雜編輯操作 ➜ cat edit.sed /hello/p ➜ sed -n -f edit.sed hello.md # -E (或 -r)支持擴展正則表達式 ➜ sed -n -E '/hello|HELLO/p' helloWorld.sh HELLO bash echo "hello world" # -i 直接修改源文件內(nèi)容 # s 是替換命令 # 這里是吧 helloWorld.sh 文件中所有的 hello 改為 hello123 sed -n -i 's/hello/hello123/g' helloWorld.sh
匹配模式(pattern)
匹配模式 | 說明 |
---|---|
10command | 第 10 行 |
10,20command | 第 10 到 20 行 |
10,+5command | 第 10 到 16 行 |
/pattern1/command | 匹配 pattern1 對應的行 |
/pattern1/,/pattern2/command | 從 pattern1 對應的行開始,到 pattern2 的行 |
10,/pattern1/command | 從第 10 行開始,到 pattern1 的行 |
/pattern1/,10command | 從 pattern1 對應的行開始,到第 10 行 |
常用編輯命令(command)
查詢
- p 打印匹配的內(nèi)容
增加
- a string 行后追加
- i string 行前追加
- r file 從外部文件讀入,在匹配的行后追加
- w newfile 將匹配的行寫入外部文件
刪除
- d 刪除
修改
- s/old/new 替換行內(nèi)第一個 old 為 new
- s/old/new/g 行內(nèi)所有 old 替換為 new
- s/old/new/2g 從第 2 行開始到文件末尾的所有 old 替換為 new
- s/old/new/ig 行內(nèi)所有 old 替換為 new,忽略大小寫
示例:
# 刪除以 sys 開頭、并且以/sbin/nologin 結尾的行 ➜ sed -i '/^sys.*\/sbin\/nologin$/d' passwd_bak # 刪除注釋行、空行 sed -i '/[:blank:]*#/d;/^$/d' passwd_bak # 查找在以 vagrant 開頭的行,下一行追加內(nèi)容 ➜ sed -i '/^vagrant/a 這是追加的一行內(nèi)容' passwd_bak # 把所有的 root 替換為 root123 ➜ sed -i 's/root/root123/ig' passwd_bak # 在所有以 sys 開頭、以 nologin 結尾的行,尾部追加 _666 # 其中 & 表示前面正則匹配到的內(nèi)容 ➜ sed -i 's/^sys.*nologin$/&_666/g' passwd_bak # 把所有以 sys 開頭、以 nologin_666 結尾的行 改為 # 以 SYS_ 開頭、以 _777 結尾,其中 \1 表示前面括號中匹配的中間部分內(nèi)容 ➜ sed -i 's/^sys\(.*\)nologin_666$/SYS_\1_777/g' passwd_bak # 把 1 ~ 10 行所有的 sys 改為 SYS ➜ sed -i '1,10s/sys/SYS/ig' passwd_bak # 統(tǒng)計 my.cnf 文件中 mysqld 的子配置項數(shù)量 # sed 查找從 [mysqld] 到 下一個[.*] 之間的行 # grep -v 過濾注釋、空行和 [.*] 行 # wc -l 統(tǒng)計最后的行數(shù) sed -n "/^\[mysqld\]$/,/^\[.*\]$/p" /etc/my.cnf | grep -Ev '^$|[#;]|^\[.*' | wc -l
注意:如果匹配模式中存在變量,則建議使用雙引號,如 sed -i "s/$OLD_STR/$NEW_STR/g" passwd_bak
到此這篇關于Shell文本處理三劍客之sed的使用的文章就介紹到這了,更多相關Shell文本處理sed內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
linux下wc統(tǒng)計文件的個數(shù)、行數(shù)、字數(shù)、字節(jié)數(shù)等信息方法
下面小編就為大家?guī)硪黄猯inux下wc統(tǒng)計文件的個數(shù)、行數(shù)、字數(shù)、字節(jié)數(shù)等信息方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05Shell實現(xiàn)程序造死循環(huán)的幾種方法示例
在linux下編程的程序猿都知道shell腳本,就算你不怎么熟悉,也應該聽過的吧!那在shell腳本中的死循環(huán)該怎么寫呢?下面這篇文章就來給大家介紹了關于Shell如何實現(xiàn)讓程序造死循環(huán)的幾種方法,需要的朋友可以參考下。2017-08-08