【demo】sed替换指定⾏的整⾏和替换指定⾏中的部分字符串【demo】sed替换指定⾏的整⾏和替换指定⾏中的部分字符串
字符串截取第几行
1.创建⽂本⽂件
输⼊以下内容:
--What's wrong?
What's wrong?
favorite.food=Orange
export favorite.food=Hamburger
2.创建脚本⽂件test.sh
touch test.sh
输⼊以下内容:
!#/bin/bash
script_path=`cd ${dirname $0};pwd`
test_file=${script_path}/
#sed替换指定⾏整⾏
line=`cat ${test_file}|grep -n "What's wrong?" |grep -v "\-\-"| awk -F: '{print $1}'|sed -n 1p`
if [ "X${line}" != "X" ];then
sed -i "${line}c Nothing is wrong!" ${test_file}
if [ $? -ne 0 ];then
echo "${LINENO}:successfully."
else
echo "${LINENO}:failed."
exit 1
fi
else
echo "Skip modify."
fi
#sed替换指定⾏中的关键字
line=`cat ${test_file}|grep -n "favorite.food="|awk -F: '{print $1}'|sed -n 1p`
if [ "X${line}" != "X" ];then
sed -i "${line}s;favorite.food*; favorite.food=Apple;g" ${test_file}
if [ $? -ne 0 ];then
echo "${LINENO}:successfully."
else
echo "${LINENO}:failed."        exit 1
fi
else
echo "Skip modify."
fi

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。