1.刪除匹配行的上一行和下一行:php
sed -i -e '/string/{n;d}' -e '$!N;/\n.*string/!P;D' filename
2.刪除匹配到特定字符所在行的上一行 html
sed -i -e '$!N;/\n.*string/!P;D' filename
3.刪除匹配到特定字符所在行的下一行 linux
sed -i -e '/string/{n;d}' filename
4.sed中使用變量,刪除匹配行的上一行和下一行:nginx
AA=string #變量指定匹配字符串 sed -i -e '/'"$AA"'$/{n;d}' -e '$!N;/\n.*'"$AA"'$/!P;D' file
a 追加內容 sed ‘/匹配詞/a\要加入的內容’ example.file(將內容追加到匹配的目標行的下一行位置)
i 插入內容 sed ‘/匹配詞/i\要加入的內容’ example.file 將內容插入到匹配的行目標的上一行位置)
示例:
#我要把文件的包含「chengyongxu.com」這個關鍵詞的行前或行後加入一行,內容爲「allow chengyongxu.cn」shell
1 #行前加 2 sed -i '/allow chengyongxu.com/i\allow chengyongxu.cn' the.conf.file 3 #行先後 4 sed -i '/allow chengyongxu.com/a\allow chengyongxu.cn' the.conf.file
給匹配到文件中具體的字符串的下一行插入一行數據:centos
sed -i '/listen/a\ listen 80\;' filename
在匹配到特定字符串的某行後批量插入多行數據:ide
sed -i '/syncsendmsg.php/a\#013.平臺廣告小時計劃每5分鐘寫入主平臺 xxx 2019-07-04\n*/5 * * * * /usr/bin/php /data/cron/ptask/countjs_syc_plan_main.php\n*/5 * * * * /usr/bin/php /data/cron/ptask/countjs_syc_plan_h_main.php' filename
給匹配到文件中具體的字符串的上一行插入一行數據:學習
sed -i '/listen/i\ listen 80\;' filename
一、刪除指定行的上一行unix
sed -i -e :a -e '$!N;s/.*\n\(.*ServerName abc.com\)/\1/;ta' -e 'P;D' file 例如: [root@VM_82_178_centos vhost]# grep listen m.afpfpm.cn443.conf listen 80; listen 443; 刪除 listen 443;這一行的上行內容: listen 80; sed -i -e :a -e '$!N;s/.*\n\(.*listen 443\)/\1/;ta' -e 'P;D' m.afpfpm.cn443.conf
二、刪除指定字符串之間的內容code
sed -i '/ServerName abc.com/,/\/VirtualHost/d' $file http://www.linuxso.com/shell/17542.html
生產中nginx配置文件替換字符
sed -i 's/#fastcgi_pass/fastcgi_pass/g;s/fastcgi_pass unix:\/dev\/shm\/php-cgi.sock/#fastcgi_pass unix:\/dev\/shm\/php-cgi.sock/g' m.6saeq.cn443.conf
今天演示到此處,歡迎留言一塊兒交流學習