Replace whole line containing a string using Sed

I have a text file which has a particular line something like

sometext sometext sometext TEXT_TO_BE_REPLACED sometext sometext sometext

I need to replace the whole line above with

This line is removed by the admin.

The search keyword is TEXT_TO_BE_REPLACED

I need to write a shell script for this. How can I achieve this using sed ?


You can use the change command to replace the entire line, and the -i flag to make the changes in-place. For example, using GNU sed:

sed -i '/TEXT_TO_BE_REPLACED/cThis line is removed by the admin.' /tmp/foo

Note: on OSX you need to install "brew install gnu-sed --with-default-names" to support GNU style -i command


您需要在前后使用通配符( .* )来替换整行:

sed 's/.*TEXT_TO_BE_REPLACED.*/This line is removed by the admin./'

The accepted answer did not work for me for several reasons:

  • my version of sed does not like -i with a zero length extension
  • the syntax of the c command is weird and I couldn't get it to work
  • I didn't realize some of my issues are coming from unescaped slashes
  • So here is the solution I came up with which I think should work for most cases:

    function escape_slashes {
        sed 's/////g' 
    }
    
    function change_line {
        local OLD_LINE_PATTERN=$1; shift
        local NEW_LINE=$1; shift
        local FILE=$1
    
        local NEW=$(echo "${NEW_LINE}" | escape_slashes)
        sed -i .bak '/'"${OLD_LINE_PATTERN}"'/s/.*/'"${NEW}"'/' "${FILE}"
        mv "${FILE}.bak" /tmp/
    }
    

    So the sample usage to fix the problem posed:

    change_line "TEXT_TO_BE_REPLACED" "This line is removed by the admin." yourFile
    
    链接地址: http://www.djcxy.com/p/47136.html

    上一篇: json和simplejson Python模块有什么区别?

    下一篇: 使用Sed替换包含字符串的整行