Linux Tips 17: Find and replace text in multiple files

|
Multiple file find and replace is a rarely used, but an extremely time saving, ability of Linux that I cannot live without. It can be achieved by chaining a few commands together to get the list of files you want to change (find), make sure the files contain the strings you want to replace (grep), and do the replacements (sed).

Lets say we have a lot of code that uses the function registerUser that was implemented when there was only one class of users, but now another class of users need to access the system and what were "users" are now called "admins" so we need to change all calls to registerUser to registerAdmin. The command needed would be:


find . -type f | xargs grep -l 'registerUser' | xargs sed -i '' -e 's/registerUser/registerAdmin/g'

The first part of the command is find, which finds all files and excludes directories. That result is then piped to grep, which lists all files that contain registerUser. The results of is then sent to sed, which replaces all occurances of registerUser with registerAdmin.

The command is quite long and hard to remember, which is why I normally write it down somewhere. Having it archived on my blog means I can just look here in the future.

2 comments:

bundacia said...

I think you can simplify that to this:

find . -type f -exec sed -i -e 's/registerUser/registerAdmin/g' {} \;

Mark Steve said...

This tips is very useful for me. I really need to understand this function and this page provide a best material to learn this process. Event App Android

Post a Comment