【demo】sed替換指定行的整行和替換指定行中的部分字符串


demosed替換指定行的整行和替換指定行中的部分字符串

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM