sed: not just for pipes and one-liners

By  

The -n prevents you from seeing all the other lines of the file as well.

If you want to replace task 11 in your tasks list, you can do it in two steps like this:

$ sed -i '11 d' tasks 
$ sed -i'' '11 i 11:  Host a sailboat party on the Bay' tasks

That may look a little more tricky than it is. Keep in mind that the second 11 is part of the text we're inserting. Read this as "at line 11, insert 11..." and so on. You can then check to see if your changes worked as intended with this command:

$ sed -n 11p tasks
11:  Host a sailboat party on the Bay

The sed command can also allow you to make global in-place edits. For example, you could change every instance of "sailboat" to "speedboat" if you decided you were tired of moving at under 10 knots.

$ sed -i s/sailboat/speedboat/ tasks

You can then verify your changes to your tasks list with a sed command that acts a lot like grep:

$ sed -n '/boat/p' tasks
11:  Host a speedboat party on the Bay
18:  Sell the speedboat for a big profile
19:  Hang a picture of the speedboat in the basement

The grep equivalent (grep boat tasks) is, of course, even easier, but it's nice to see that sed has this much flexibility. In fact, sed is not just a tool for one-liners, but can be used for standalone scripts like these:

For double spacing text in a file:

#!/bin/sed -f
#dbl: double-space a text file
G

For changing one string to another in a specified range of lines (in this case, Linux or linux to "Unix or Linux" in the first three lines:

#!/bin/sed -f

1,3{
      s/[Ll]inux/Unix or Linux/g
}

It's been a long time since my first O'Reilly "sed & awk" book, but I still find that it's fun to see what I can do with these commands.

Photo Credit: 

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Operating SystemsWhite Papers & Webcasts

See more White Papers | Webcasts

Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question