User Tools

Site Tools


howto_sed

SED

Is like a swiss army knife in Linux, it is a very powerful command line tool that you can use to edit text files, while the following example is dead simple I cannot overstate sed's usefulness enough, dive into it.

The following is an example:

sed -e 's#P#{{http://mysite.org/download/images/P#g' test.txt > test1.txt

What is happening in the line above, well you are telling SED to search a file test.txt for the phrase P

Once SED has found that phrase it must replace the phrase with the following text:

 {{http://mysite.org/download/images/P//

Additionally to the SED commands I've added a > test1.txt to the command line

What this does is to actually write the changes to a file, I choose a different file name to avoid destroying the original in case I make a mistake.

There is one more thing!

You might have noticed a # in several places.

The # is used as a delimiter, you could substitute the # for other characters in case your text contained a #, just make sure that the delimiter you choose does not exist in the text and that it is not forbidden by SED type man sed for a more in depth explanation of what sed can do for you, and experiment with putting it into larger and more advanced scripts.

But what was the above used for.

This example is based on a time I used SED to parse a list of almost thousand filenames in order to have a page built for a wiki, you can use SED in much more advanced ways than explained here, but the idea is to give you a taster of how you can make your machine work for you.

The Original file looked like this:

P001.png
P002.png
P003.png
P004.png
P005.png
P006.png
P007.png
P008.png

After running SED on it with the above line it looked like this:

{{http://mysite.org/download/images/P001.png
{{http://mysite.org/download/images/P001.png
{{http://mysite.org/download/images/P002.png
{{http://mysite.org/download/images/P003.png
{{http://mysite.org/download/images/P004.png
{{http://mysite.org/download/images/P005.png
{{http://mysite.org/download/images/P006.png
{{http://mysite.org/download/images/P007.png
{{http://mysite.org/download/images/P008.png
{{http://mysite.org/download/images/P009.png

I did some other things to the text as well, but that is irrelevant for this example which was only intended to show what you can do with rudimentary use of sed.

howto_sed.txt · Last modified: 2012/03/09 10:43 (external edit)