sed替换
1. sed可以替換給定的文本中的字符串,可以利用正則表達式進行匹配
$ sed 's/pattern/replace_string/' file
或者
$ cat file | sed 's/pattern/replace_string/' file
使用-i選項,可以將替換的結果應用于原文件,也可以借助重定向來保存文件:
sed 's/text/replace/' file > newfile
其實可以使用
sed -i 's/pattern/replace_string/' file
后綴/g意味著替換每一處,有時候不需要替換前N處匹配,有一個選項可以用來忽略前N處匹配,并從第N+1處開始替換。
$ echo this thisthisthis | sed 's/this/THIS/2g'
$ echo this thisthisthis | sed 's/this/THIS/3g'
當需要從第N處開始匹配時,可以使用/Ng
字符/在sed中作為定界符使用,也可以用其他字符代替。
1. 刪除空白行
sed '/^$/d' file
2. 已匹配的字符串標記&
echo this is an example | sed 's/\w\+/[&]/g'
正則表達式\w\+匹配每個單詞,然后用[&]來替換它,&對應于之前所匹配的單詞。
3. 子串匹配標記\1
&代表匹配給定樣式的字符串,但我們也可以匹配給定樣式的其中一部分
echo this is digit 7 in a number | sed 's/digit \([0-9]\)/\1/'
這條命令將digit 7 替換成7,樣式中匹配到的子串是7,\(pattern\)用于匹配子串,模式被包括在使用斜線轉義過的()中,對于匹配到的第一個子串,其對應的標記是\1,匹配到的第二個子串是\2,往后依次類推,下面示例中包含了多個匹配:
echo seven EIGHT | sed 's/\([a-z]\+\) \([A-Z]\+\)/\2 \1/'
4. 引用
$text=hello
echo "hello world" | sed "s/$text/HELLO/"
5. 追加內容 sed ‘/匹配詞/a\要加入的內容’ example.file(將內容追加到匹配的目標行的下一行位置)
i 插入內容 sed ‘/匹配詞/i\要加入的內容’ example.file 將內容插入到匹配的行目標的上一行位置)
示例:
#我要把文件的包含“chengyongxu.com”這個關鍵詞的行前或行后加入一行,內容為“allow chengyongxu.cn”
行前加
sed -i '/allow chengyongxu.com/i\allow chengyongxu.cn' the.conf.file
行前后
sed -i '/allow chengyongxu.com/a\allow chengyongxu.cn' the.conf.file
6. 刪除指定行的上一行
sed -i -e :a -e '$!N;s/.*\n\(.*ServerName abc.com\)/\1/;ta' -e 'P;D' $file
刪除指定字符串之間的內容
sed -i '/ServerName abc.com/,/\/VirtualHost/d' $filehttp://www.linuxso.com/shell/17542.html
7. 也可在vi模式下,將文本中的內容替換,esc : %s/dog/sdog/ 這樣可以把文件直接修改,然后保存即可
在vi模式下也可進行區間替換,如將第2至第7行之間的cat 換成scat,esc : 2,7 s/cat/scat/ 同樣保存修改即可
8. sed查找行,如查找出vsftpd.conf中的非注釋行
[root@server4 shell]# cat vsfptd.conf | sed '/#/d'
刪除空格行和以#號開頭的行,并寫入文件vsftpd.config,用-e開關連接兩個控制語句
[root@server4 shell]# cat vsfptd.conf | sed -e'/^#/d' -e '/^$/d' >vsftpd.config
9. sed刪除匹配的行的后續多行
$sed '/Storage/,+2d' thegeekstuff.txt
sed刪除匹配行到尾行
$sed '/Website Design/,$d' thegeekstuff.txt
sed刪除匹配行到首行
轉載于:https://www.cnblogs.com/forilen/p/4387706.html
總結
- 上一篇: 实战SQL Server 2005镜像配
- 下一篇: 【三电平SVPWM学习