Thursday, April 17, 2008

External editing of the files in Unix

While debugging a build break, I came across some scripts which were strangely named with extension .ed. Just out of curiosity I opened one of them and I was taken aback by the contents. I just wondered to myself how the hell did I never knew this?

It was using ex (actually just a command line interface to vi), which I now realize is such a powerful tool to edit files without actually opening them in editor window one by one. Let me give you a small example of how to use it. That ease of use will demonstrate its awesome powers.

Lets say you have a file named, abc.txt. The contents of the file are

Solaris
Linux
Hpux
Aix
Windows

Now lets say you want to replace string Windows with Apple. You can write one script named replace.ed which will look something like this:

#####SCRIPT BEGINS#####
#!/bin/sh
TERM=vt100
export TERM
ex -s $1 "<<" MYEOF >/dev/null
set noignorecase
%s/Windows/Apple/g
.
w
q
MYEOF
#
exit 0
##### SCRIPT ENDS#####
Now, all you have to do is to run the script by providing the file to be edited as an input.
bash-2.05$./replace.ed abc.txt

The utility example that I have displayed here is pretty simple, but surely good enough to emphasize the power of this tool. Just imagine how quickly and automatically you can do search and replace text for n number of files by calling this script from some iterative loop.

Happy Editing!

No comments: