【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