Blog is moving

My blog is moving to http://victormendonca.com/blog/. If you are looking for a specific or older post you are in the right place Otherwise check out my new page for more up to date content.

Tuesday, June 29, 2010

Using Variables on a sed Expression

Using variables as a matching pattern on a sed expression can be tricky. Take a look at the examples below.

Here's the value for PATH and HOME on this example system:
$ echo $PATH
/home/victor/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
$ echo $HOME
/home/victor

Let's say we would like to use the value of HOME to change the string “/home/victor/bin” to “/bin”. A few attempts would look like this:
$ echo $PATH | sed 's/"$HOME"//'
/home/victor/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

$ echo $PATH | sed 's/$HOME//'
/home/victor/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

$ echo $PATH | sed s/$HOME//
sed: -e expression #1, char 9: unknown option to `s'

However if we use a colon “:” as the field delimiter instead of a forward slash “/”, the desired result can be achieved very easily:

$ echo $PATH | sed s:$HOME::
/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

Removing Windows Newline (Control) Characters on VI

If you have to work on a Unix box trough Windows (putty or any other ssh utility), you most likely have encountered the problem where pasting a text trough putty will result on Windows control characters (^M) at the end of the lines. This is actually very easy to fix.

1- Open the text with VI (or VIM)
$ vi {file_name}

2- Now we need to get in command mode by pressing colon “:” on your keyboard
3- Type in the following code (note that you to get ^M you need to press “Ctrl+v” and then “Ctrl+m” on your keyboard):
%s/^M//g

4- Hit enter and you should be good to go!!


Related links:
http://en.wikipedia.org/wiki/Newline
http://www.cs.colostate.edu/helpdocs/vi.html