what's the best way to do this? I'm no command line warrior, but I was thinking there's possibly a way of using grep
and cat
.
I just want to replace a string that occurs in a folder and sub-folders. what's the best way to do this? I'm running ubuntu if that matters.
You can use it like this:
Supply no paths to make it use the current directory. Note that ag, xargs, and perl need to be installed and on PATH.
The first part of that is a find command to find the files you want to change. You may need to modify that appropriately. The
xargs
command takes every file the find found and applies thesed
command to it. Thesed
command takes every instance of from and replaces it with to. That's a standard regular expression, so modify it as you need.If you are using svn beware. Your .svn-directories will be search and replaced as well. You have to exclude those, e.g., like this:
or
An alternative to
sed
is usingrpl
(e.g. available from http://rpl.sourceforge.net/ or your GNU/Linux distribution), likerpl --recursive --verbose --whole-words 'F' 'A' grades/
As Paul said, you want to first find the files you want to edit and then edit them. An alternative to using find is to use GNU grep (the default on Ubuntu), e.g.:
You can also use ack-grep (sudo apt-get install ack-grep or visit http://petdance.com/ack/) as well, if you know you only want a certain type of file, and want to ignore things in version control directories. e.g., if you only want text files,
An alternative to using sed is to use perl which can process multiple files per command, e.g.,
Here, perl is told to edit in place, making a .bak file first.
You can combine any of the left-hand sides of the pipe with the right-hand sides, depending on your preference.
I'll throw in another example for folks using
ag
, The Silver Searcher to do find/replace operations on multiple files.Complete example:
If we break this down, what we get is:
Next, we have:
Finally, the string replacement command: