Sed? Long live “replace”!

Danila Vershinin
May 22 · 2 min read

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.

replace2

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 https://extras.getpagespeed.com/release-el$(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.

Originally published at GetPageSpeed.

Danila Vershinin

Written by

Performance Oriented DevOp