User Tools

Site Tools


howto_sed

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

howto_sed [2012/03/09 10:43]
howto_sed [2012/03/09 10:43] (current)
Line 1: Line 1:
 +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:
 +
 +<code>
 +sed -e 's#P#{{http://mysite.org/download/images/P#g' test.txt > test1.txt
 +</code>
 +
 +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:
 +
 +<code> {{http://mysite.org/download/images/P//
 +</code>
 +
 +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:
 +
 +<code>
 +
 +P001.png
 +P002.png
 +P003.png
 +P004.png
 +P005.png
 +P006.png
 +P007.png
 +P008.png
 +
 +</code>
 +
 +After running SED on it with the above line it looked like this:
 +
 +<code>
 +{{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
 +</code>
 +
 +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)