Friday, May 11, 2007

Linux: The replace command

The linux replace utility is a very useful command for performing string substitutions, which I find much easier to use than sed. It has a much simpler syntax, performs the substitution in place (unlike sed which leaves the input file intact) and allows you to carry out multiple string substitutions in a series of files at once.

The basic syntax for the command is:
replace from to [from to] ... -- file [file] ...
The man page can be found here, although the usage is very simple. You first specify an arbitrary number of from-to string pairs. These strings can be placed in quotes if they contain spaces and other special characters. I am not sure at the moment if replace supports regular expression (of which I am not a really big fan, so I don't really mind :P). The '--' delimiter signals the end of the list of substitution pairs and is followed by the list of files that will be edited.

Example:
replace foo bar one two -- index.html
This command will replace all occurrences of "foo" in file index.html with "bar" and all occurrences of "one" with "two".
The replace command returns a notification on which files were actually converted. It does not report how many changes were made to each file or anything more detailed, but still the piece of information it does return is quite useful.

One disadvantage I find in replace is that it doesn't have an option to recursively access and edit files. One workaround is to feed it with the output of a grep -l command, eg.
replace foo bar -- `grep -l foo *`

Unfortunately, the replace utility is not usually installed by default on linux systems; it was designed to be used by the msql2mysql utility, therefore it is installed only when mysql is installed.

No comments: