Using sed to replace words in a file

6 02 2008

So there’s actually a story behind this :lol:

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 :lol:

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! :oops: :shock: :lol:


Actions

Information

5 responses

7 02 2008
novaaesa

That’s a good one to remember.

I use a different technique in the .conkyrc though. Instead of using hex numbers like FF6600 in the color tags, I have color declarations just before the TEXT part.

E.g. I could have:
color1 447788
color2 110099
color3 334477

And then under the TEXT part, instead of using ${color 447788} to change to the color I want, I just use ${color1} instead (or you can leave out the brackets). Then, when you go through and want to change colors, you can just do it at the top. :)

Anyway that’s my way of doing it, but using sed seems just as good :P

7 02 2008
linuxtechie

Interesting. I never thought of doing it that way. That’s a good way to do it. ;)

3 06 2009
Alex Zubin

How do I replace only if the keyword is at the begining of a line?

Code:
—-
a = “This is a print statement”
print(a)
—-
What if I want to replace print by #print only in the second line i.e only if the line starts with that keyword.

Please help me out. I’m new to SED.

22 07 2009
Nick

“s/^print/replacement/”

22 07 2009
Nick


but you really need to get used to regexps
at least enough to understand what’s the difference between
“s/^print/replacement/”
and
“s/^ *print/replacement/”

Leave a comment