Skip to content

Instantly share code, notes, and snippets.

@alobato
Created May 11, 2010 22:46
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save alobato/397992 to your computer and use it in GitHub Desktop.
Save alobato/397992 to your computer and use it in GitHub Desktop.
Find and replace text in multiple files
# Find and replace text in multiple files
# http://www.24hourapps.com/2009/03/linux-tips-17-find-and-replace-text-in.html
# 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.
@matshovin
Copy link

Cool

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment