Skip to content

A hidden gem in the MySQL distribution: replace

Since the very early days, the MySQL distribution packages contain a very useful commandline-tool named replace. As the name implies, it can be used to replace strings in text files. From the documentation:

The replace utility program changes strings in place in files or on the standard input. Invoke replace in one of the following ways:
shell> replace from to [from to] ... -- file [file] ...
shell> replace from to [from to] ... < file
from represents a string to look for and to represents its replacement. There can be one or more pairs of strings. Use the -- option to indicate where the string-replacement list ends and the filenames begin. In this case, any file named on the command line is modified in place, so you may want to make a copy of the original before converting it. replace prints a message indicating which of the input files it actually modifies. If the -- option is not given, replace reads the standard input and writes to the standard output. replace uses a finite state machine to match longer strings first. It can be used to swap strings. For example, the following command swaps a and b in the given files, file1 and file2:
shell> replace a b b a -- file1 file2 ...

This comes in very handy, especially if you need to replace a similar text in a large number of files, or if you need to replace multiple different strings in a file at the same time! So next time you need to replace strings in text files, take a look at this hidden gem!

Unfortunately the string matching does not support regular expressions - but the source code actually documents some additional options:

Special characters in from string:
^ Match start of line.
\$  Match end of line.
\b  Match space-character, start of line or end of line.
        For end \b the next replace starts locking at the end space-character.
        An \b alone or in a string matches only a space-character.
\r, \t, \v as in C.

The programs make a DFA-state-machine of the strings and the speed isn't
dependent on the count of replace-strings (only of the number of replaces).
A line is assumed ending with \n or \0.
There are no limit exept memory on length of strings.

 

 

 

 

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

Jeff Stoner on :

Add Comment

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
Standard emoticons like :-) and ;-) are converted to images.
HTML-Tags will be converted to Entities.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

Form options
tweetbackcheck