【demo】sed替換指定行的整行和替換指定行中的部分字符串
1.創建文本文件 test.txt
touch test.txt
輸入以下內容:
--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}/test.txt
#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