recursive search and replace old with new string, inside files

$ grep -rl oldstring . |xargs sed -i -e 's/oldstring/newstring/'
recursively traverse the directory structure from . down, look for string "oldstring" in all files, and replace it with "newstring", wherever found also: grep -rl oldstring . |xargs perl -pi~ -e 's/oldstring/newstring'

2009-03-03 20:10:19

5 Alternatives + Submit Alt

What Others Think

so sweet and delicious
linuxrawkstar · 636 weeks ago
egrep might be better in some cases
linuxrawkstar · 636 weeks ago
find . -type f -exec grep -l XXX {} \;|tee /tmp/fileschanged|xargs perl -pi.bak -e 's/XXX/YYY/g' Find all files that contain string XXX in them, change the string from XXX to YYY, make a backup copy of the file and save a list of files changed in /tmp/fileschanged.
drossman · 635 weeks and 5 days ago
find -type f | xargs sed -i -e '/oldstring/s,oldstring,newstring,'
rbossy · 601 weeks and 5 days ago
grep before using sed is unnecessary, it causes all files to be read and processed TWICE instead of just once. Just use find and sed.
SlimG · 596 weeks ago
If you can install "rpl", have a look at man rpl. It does the same job more simply. I don't know how it would compare for speed though.
johnraff · 596 weeks ago
if you do this on a directory using subversion, ignore the .svn directories, or you'll get a surprise when asking for svn status.
zaninottof · 574 weeks and 2 days ago
this command has worked in all cases I've tried it on. I prefer to use fgrep, however. find also works nicely
bbrraacckk · 410 weeks ago
If you want to make sure you haven't already processed the line you can use this: grep -rLZ newstring . |xargs -0 sed -i -e 's/oldstring/newstring/' The -L tells grep to invert the search (-v doesn't do what you want) and the grep -Z and xargs -0 go together to ignore whitespace and allow spaces in filenames.
mrwulf · 392 weeks and 5 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this? is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.


Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: