The very powerful sed command

Have you ever needed to replace a string in a file or multiple files? Why not try it without opening a file?

I do a lot of web design. Every so often, I will have a string or a variable in a web page which is in there many times. Even more often, the same string will be in multiple files – multiple times. This occurs most often in plain HTML code. However, there are often times where it happens in a regular text document or a configuration file. The best example of this is Conky which is a program that allows you to “code” a desktop widget. In my Conky script, I had the color red in the file many times – about 10 times. I’m sure I could probably use a variable and only have to change the color in one place, but I haven’t gotten to the point where I know how to make a variable in Conky. So, for instance, the following line might be in my Conky script 10 times:

${color F00}This is red text${color}

Going through each line to change the color to green (0F0) can be very redundant, and this is where sed comes to the rescue.

Follow these steps to get a good working example of sed:

  • Open up the Linux/Unix terminal of choice
  • enter these commands:
touch sed.txt
echo "a b c d e f g h i j k l m n o p q r s t u v w x y z" > sed.txt

Now that we have a file to work with, let’s replace the letters l, m, and n with your name:

sed -i 's/l m n/Kris/g' sed.txt

From what I understand, the -i makes sure the file is saved with the changes. The s searches for all of the strings that match “l m n” and replaces them with Kris. The g makes sure that it goes to the end of the current line – for each line.

Your name should now be in the file instead of the l, m, and n. Let’s check to make sure:

cat sed.txt

sed is very powerful and can do things beyond what I have shown here. To learn more about sed, take a look at its man page.
man sed



Comments are closed.

Post Navigation