读书人

sed删除指定行的下一行

发布时间: 2012-07-03 13:37:43 作者: rapoo

sed删除指定行的上一行
有这么一个需求,需要从若干个apache虚机配置文件中删除一段内容,类似下面这种

<VirtualHost *>        ServerName abc.com        DocumentRoot /home/apache/abc        CustomLog logs/abc.com-access_log combined</VirtualHost>


思路:以ServerName为中心,删除上面的一行,再删除从ServerName到</VirtualHost>之间的内容即可。

脚本如下:
#! /bin/sh# by logo32.iteye.com# delete domain from *.confDir="/usr/local/apache2/conf"cd $Dirls *.conf | while read filedocon=`grep 'ServerName abc.com' $file | wc -l`if [ $con -gt 0 ];thenecho "delete domain in this file : $Dir/$file"sed -i -e :a -e '$!N;s/.*\n\(.*ServerName abc.com\)/\1/;ta' -e 'P;D' $filesed -i '/ServerName abc.com/,/\/VirtualHost/d' $fileelseecho "======== no change for file : "$filefidone


其中最重要的两条语句
1、删除指定行的上一行
sed -i -e :a -e '$!N;s/.*\n\(.*ServerName abc.com\)/\1/;ta' -e 'P;D' $file
2、删除指定字符串之间的内容
sed -i '/ServerName abc.com/,/\/VirtualHost/d' $file

读书人网 >操作系统

热点推荐