Server Setup

Sed? Long live “replace”!

by , , revisited on

Users of various MySQL distributions know and love the replace command line utility that is shipped with MySQL servers. It allows to quickly replace a string within files.

For example, to replace string foo with bar within file.txt, you would run:

replace foo bar -- file.txt

Surely, you can do this with sed:

sed -i 's@foo@bar@g' file.txt

But for various reasons, and namely the syntax, many users want something simple like replace for the task.

The replace is most useful when you need to make multiple replacements. Simply specify multiple replacement pairs like this:

replace foo bar aaa bbb ccc ddd -- file.txt

This would replace aaa with bbb, ccc with ddd in addition to foo -> bar replacement.

Deprecation of replace utility

Some MySQL distributions now issue a warning when running the replace utility, e.g.:

Warning: replace is deprecated and will be removed in a future version.

Fear not, there is an alternative. And it’s not sed.


There is another utility for the job that is named exactly the same (replace) and it’s authored by Richard K. Lloyd.

You can get the utuility for CentOS / RHEL with a couple of commands:

yum install$(rpm -E %{rhel})-latest.rpm
yum install replace2

The program uses quite a different syntax to that of MySQL’s replace, but it’s still easier than using bare sed for the job. To remove confusion with replace, it is packaged as replace2.

To make our foo -> bar replacement, we can now run:

replace2 foo bar file.txt

And for multiple replacement pairs, put them in extra -a switches:

replace2 foo bar -a aaa bbb -a ccc ddd file.txt

The important gotcha here is that the replace2 is case insenstive by default. To make it case sensitive, use -e switch:

replace2 -e foo bar -a aaa bbb -a ccc ddd file.txt

It would be interesting to write an “alias-like” program that would be able to invoke replace2 with the same syntax and case sensitivy as its MySQL counterpart.

… and back to replace

The original MySQL version of replace utility now can be installed separately! I have built a separate package for it.

So anyone who’s missing good old replace with the exact same syntax as before can install it. If you already upgraded to MySQL 8.0 which lacks replace, or simply want to run replace on a server without MySQL installed, now you can:

yum install$(rpm -E %{rhel})-latest.rpm
yum install replace

… And rock and roll! Proceed with replacing stuff as usual 🙂

Also published on Medium.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.