Combining both find
and sed
to find and replace words
find app db spec -type f \( -name '*.rb' -o -name '*.sql' \) -exec sed -i '' -e 's/dollar_value/budget_value/g' {} \;
This script:
- searches in the
app
,db
, andspec
directories - it only looks at file types that are either
.rb
or.sql
files - it replaces the word
dollar_value
with the wordbudget_value
The start of the find command
These are the directories to look in from your current location. You could replace this with ./
to look in ANY directory
This tells find what type of object you'd like to find. f
is for 'file'. Others common options include d
for directory, or l
for symbolic link.
This is a fancy type of parameter that lets us look at multiple options. There's a couple things going on here so this section is broken up further below.
\( <rest-of-script> \)
We need to wrap it in brackets, which also need to be escapped.-name '*.rb'
Look for any file whose names ends in.rb
. We can replace-name
with-iname
if we don't care about case sensitivity- o
This is theOR
operator. In this example we are going to look for another type of file on top of ruby files.-name '*.sql'
Same as the one above, just looking to sql files instead of ruby files
This tells find that we we should like to execute a script on each result the find
command returns.
This is the start of the sed
command
In OSX, we have to tell it what we want it to do with the original content (what we are replacing). By simply giving it an empty string, we are telling it to discard it.
If we wanted to store it somewhere, you could give it something like .bak
and it will create a copy of the original file and append it with a .bak
extension.
Tell sed that we are giving it a regular expression we should like it to evaluate
Regular expression. Find this, replace with this. /g
means replace all occurances on a line, rather than just the first.
find ./ -type f -iname '*link*' -exec sed -i '.bak' -e 's/dollar_value/budget_value' {} \;
This script:
- searches in all directories
- looks for files with the word 'link' in the name regardless of case
- replaces the word
dollar_value
with the wordbudget_value
, but only the first occurance on a line - makes a copy of the files before it changes with a
.bak
extension