A tiny script to replace all occurrences of a string in a file with another string

sed -i 's/original/new/g' filename.txt

This basically replaces every occurrence of the “original” string with the “new” string in the file named “filename.txt”

e.g.

sed -i 's/192.168.0.1/192.168.1.1/g' /etc/fstab

Will replace all occurrences of the IP “192.168.0.1” with the IP “192.168.1.1” in the “/etc/fstab” file.

That’s it, Enjoy!

Sources: 

About SoCRaT

Research Support and Infrastructure Engineer, OSS & Linux Geek
This entry was posted in Linux and tagged , , , . Bookmark the permalink.

One Response to A tiny script to replace all occurrences of a string in a file with another string

  1. ΞXΤЯ3МΞ says:

    Hey SoCRaT.

    Just an additional tip on a side note escpecially when if you are working with lots of linux configs.

    If the text that you are trying to replace contains special characters, you can use backslash (\) to escape. Here is an example:

    -Lets say you have a file called “test.txt” with text “abc/e123”
    # cat test.txt
    abc/e123

    Now if you want to replace string “abc/e” with “abcde”, you can use the same command with a backslash before the special character (in this case the forward slash):

    # sed -i ‘s/abc\/e/abcde/g’ test.txt

    Now, the text would be replaced along with the special character will be parsed and replaced.

    # cat test.txt
    abcde123

    Hope this helps! Have a great day!

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s