Posts Tagged ‘command-line’

Cleaning source code with sed

Recently a ticket came across my desk to remove references to Google Plus from a set of email templates our team maintains. With dozens of email templates, I wanted to stretch my command line muscles and see if I could do it all at once.

macOS includes sed, the stream editor, and for this project I’m going to use a very simple set of commands.

Delete lines that match

d is for delete. To use this command, you have a regex, followed by the letter d. It will delete any line that matches.

For example:

sed -i.bak '/googlePlusIcon/d' someFile.txt

Substitute lines

s is for substitute. Think of it like “find and replace” except we are going to find something everywhere. There are 2 parts, a regex to match, and a regex

sed -i.bak 's/googlePlusIcon/twitterIcon/g' someFile.txt

Doing multiple files at once

You can do multiple files at once by combining find with sed. Find syntax is as follows:

find path expression

path is the scope where find will… find things. expression is a set of options to control what we match. For example, -name is to match on the filename.

Another use of expressions is to do some operation. -exec is for executing another command. In this case we want to execute sed. So we type out the sed command from above, except with a few changes. There are curly braces {} which tell find to put the filename of the match in there. There is also the \; which tells find where the -exec expression is ending.

find . -name '*.txt' -exec sed -i.bak 's/googlePlusIcon/twitterIcon/g' {} \;

One quirk about find + sed is that it likes to add newlines to the end of your files. If you are using source control like git, this may cause the diff to be slightly larger than you expected.