The most common usage of sed

terminal.png

make a file with your favorite text editor. Name this file “old” and place the word “day” within it. Save it in your home directory. /home/<username>.

Now in a shell run:

sed s/day/night/ old >new

Now you will have a file called “new”. Open that file and it should have changed the word day to night.

Re-edit the file “old” and make it look like this:

day day day

day

day

Save the file.

This time we’ll run a similar command

sed s/day/night/ old>new.2

When viewing the file new.2 you will see this:

night day day day

night

night

You will notice only the first field in each line got changed. Most Unix utilties work on files, reading a line at a time. Sed, by default, is the same way. If you tell it to change a word, it will only change the first occurrence of the word on a line. You may want to make the change on every word on the line instead of the first.

sed s/day/night/g old>new.3

Now if you view the new.3 file, every instance of day should have turned to night:

$ cat new.3

night night night night

night

night

The ‘g’ option tells sed to run globally and not for the first instance within each line.

This is my very over simplified take on sed. Please see the link above and the sed man page for more. Feel free to talk about it

For a more advanced look at Sed please see here: http://www.grymoire.com/Unix/Sed.html

No Posts Found

Comments are closed.