Refactoring with sed

In case anyone forgot, there’s a perfectly good tool for refactoring that is probably installed on your (unix-based) computer. It’s called sed and it stands for “stream editor”.

Here’s how to use it to do a search and replace across multiple files:

sed -i "" 's/uc.User.Data.ApiKey/uc.User.ApiKey()/g' **/*.go

The -i flag tells sed to edit the files in place, and the "" argument is for the file extension for backups. Since it is an empty string, no backups will be created. If you’re nervous or shaky on your version controll skillz, give it an extension. The s/.../.../g should look familiar: substitute anything that matches the first part with the second part, and the g tells it to replace all occurrences. The **/*.go recursively finds all the files ending in .go, which is probably a zsh-only wildcard.

If you don’t use zsh or you want finer control of the files, you can use find:

find . -name "*ser*.go" -exec sed -i "" 's/xxx.Log/xxx.Warn/g' {} \; -print

I never understood why people use xargs with find

sed can do a lot of other stuff:   man sed for more info…


Comments? Send us a tweet.

Permalink:

Previous:
Time Any Function in Go
Next:
Time Every HTTP Request Using net/http in Go