sed是一种流编辑器,它是文本处理中非常中的工具,能够完美的配合正则表达式使用,功能不同凡响;主要用来自动编辑一个或多个文件;简化对文件的反复操作;编写转换程序等。
本文旨在使用shell脚本和sed命令完成如下任务:
1. 插入内容
2. 删除内容(uncomment a line)
3. 修改值
源文件内容如下:
#please insert a line below
#please uncomment the line below
#SELINUX=DISABLED#please change the value 0 to 1
enabled=0
对应脚本如下,将上面的内容复制到testtxt文件中后,以下脚本便可执行:
#!/bin/bash
# define var
targetfile='/home/ubuntu/shell/testtxt'
logfile='/home/ubuntu/shell/log'
# the line below is for recovering the targetfile with a bak file
#cat /home/ubuntu/shell/bak > $targetfile
#echo "success recover the $targetfile"
# create or clear log file
echo 'start check or create log file....'
if test ! -e $logfile;
then
touch $logfile
if test $? -eq 0;then echo 'create a log file'; echo 'created by notitle'>$logfile;fi;
else
echo 'clear by notitle' > $logfile
echo 'cleared log file'
fi;
# insert a line below a given line
echo 'start insert a line...'
sed -i '/insert/a\this is a insert line' $targetfile
if test $? -eq 0;then echo 'success insert a line';echo 'insert a line' >> $logfile;fi;
# uncomment a line below a given line
echo 'start uncommnet a line...'
sed -i '/uncomment/{n;s/#//;}' $targetfile
if test $? -eq 0;then echo 'success uncomment a line';echo 'uncomment a line' >> $logfile;fi;
# change a value below a given line
echo 'start change a value....'
sed -i '/change/{n;s/0/1/;}' $targetfile
if test $? -eq 0;then echo 'success change a value';echo 'change a value 0 to 1' >> $logfile;fi;
# finished all deal
echo 'finished all'
参考sed学习地址http://man.linuxde.net/sed