SED – Find and Replace a String in a File

The substitution option is one of the most useful options of a sed command.

In particular, it allows to search a text file for lines that contain particular string (SEARCH_STRING), word or match some regular expression and replace all occurrences of such lines with some REPLACEMENT_LINE.

To replace the whole line using sed, it is needed to add wildcards (.*) before and after a SEARCH_STRING.

SED – Find and Replace a String in a File

Use the following sed command to search each line of a FILE for a SEARCH_STRING and replace each matched line with REPLACEMENT_LINE:

$ sed -i 's/.*SEARCH_STRING.*/REPLACEMENT_LINE/' FILE

The options passed to the sed command:

Option Description
-i Edit FILE in place
s/ Substitute each line that contains SEARCH_STRING with REPLACEMENT_LINE
Was it useful? Share this post with the world!

3 Replies to “SED – Find and Replace a String in a File”

  1. Be careful if you replace URLs with “/” character.

    An example of how to do it:

    $ sed -i "s%http://domain.com%http://www.domain.com/folder/%g" "test.txt"

    Extracted from: http://www.sysadmit.com/2015/07/linux-reemplazar-texto-en-archivos-con-sed.htm

  2. Для подставки URL в sed мне помогло
    #!/bin/bash
    path=”what_replace = http://example.com
    sed -i “s#.*what_replace.*#$path#g” filename

  3. thanks a lot

Leave a Reply