Tag Archives: edit

Using sed to replace words in a file

So there’s actually a story behind this 😆

My conkyrc file has grown to a fairly large size and it’s a bit of a pain to go through it to change the colors. After all there’s lots of ${color} in it 😆

So I needed a command that could do this for me. That’s when I found sed, a stream editor. sed can replace a word or set of words with a different word or set of words.

There’s a couple different ways to use sed. You can have it replace only the first instance of a word in a sentence or you can have it replace the word globally.

To replace only the first instance of a word in a sentence the command looks like this

sed -i ‘s/original_word/new_word/’ file.txt

To change all instances of a word in a file the command is

sed -i ‘s/original_word/new_word/g’ file.txt

the “g” at the end tells sed to perform the action globally.

You can also do more than one word, like a phrase. To do this correctly you need to use a “\” backslash before the space. So for example I wanted to replace all instances of “black” with “light blue” in my conkyrc. This is what the command looked like

sed -i ‘s/black/light\ blue/g’ .conkyrc

That saved me about 5 minutes of editing my conkyrc.

So there you have it, a very useful time saving command.

Or you can use the Replace button in Gedit which somehow I managed to overlook while trying to figure out a command to do this! 😳 😯 😆