Sunday, May 6, 2012

sed basics

If you often have to modify some configuration files like fstab, menu.lst, bashrc, etc by removing lines, change some device or comment/uncomment one or more lines, "sed" will be the simplest and fastest way to do so without needing to open the files with an editor.
But first you will have to know a few thing about the "sed" command.

One of the most common uses o f "sed" is to replace one string by another, maybe a device name or the path for something.

From the sed man page:

              Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement.

Here is an example changing /dev/sda with /dev/sdb in /etc/fstab:

Now lets comment out my samba share line:

Note you will have to escape the "/" characters with a leading "\".

Deleting empty lines is just as easy as follows:

Note the "^" character stands for "Line start" and "$" for "End of line" so "^$" means "blank line". Those special character are oftern used in regular expression matching. Take a look at my grep post to see more examples of using regular expessions.

You can also make sed to work on a specific line or range. I created a file with binary numbers 0-16 to work on it.
I will use "nl" to show line numbers from now on to make it easier to see what lines where affected by sed.

Deleting line 8 (0111):

Deleting range 4-13:

If there is a string that repeats many times and you want to change just one specific apparition on a specific line:

Lets change "FF" whith "--"on range 2-3 3rd apparition and range 5-9 6th apparition:

Note you can concatenate sed commands with "-e".

Sed is a very powerfull tool and can do much more complex tasks than the ones exposed in this post. It will take some time to learn his usage but on the long run using sed will speed up many repetitive tasks on the command line.

1 comment:

  1. Great post, it have everything one need to know about coding, going to share it with my circle of friends, thank you for sharing it and keep posting more such stuff.