Use grep And sed To Search And Replace Text, But Beware Git

I recently needed to search and replace some text in a large number of PHP scripts. Back in my Windows days I had a lightweight freeware programme that was perfect for the job. But what to do on Linux? The answer was to combine grep and sed. But don’t forget to watch out for Git!

grep And sed

grep is a command-line utility for searching plain-text data sets for lines matching a regular expression. sed (stream editor) is a command-line utility that parses and transforms text. Put the two together by piping the output from grep to sed and you’ve got a command-line search and replace tool!

How To Search And Replace

The intricacies of grep and sed are beyond the scope this post. Suffice it to say, the snippet below will do the searching and replacing for you:

grep -rl matchstring | xargs sed -i 's/matchstring/replacestring/g'

Don’t Get Caught By Git!

In my haste to update my PHP files I neglected to notice that as well as matching my scripts, grep had also matched a Git index file .git/index. So when I ran piped the result to sed, the Git index was updated and it broke my repository! No git status or any of the familiar Git commands would work.

Exclude The Git Directory

When running your grep command it is possible (in modern versions >= 2.5.2) to use the --exclude-dir='pattern' option. So in my case it would have been:

grep -rl --exclude-dir='.git' matchstring | xargs sed -i 's/matchstring/replacestring/g'

Useful Links

Leave a Reply

Your email address will not be published. Required fields are marked *