shell脚本——sed

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值