Skip to content

Instantly share code, notes, and snippets.

@hackling
Last active August 29, 2015 14:09
Show Gist options
  • Save hackling/f04a92bfdd2ced53f1dd to your computer and use it in GitHub Desktop.
Save hackling/f04a92bfdd2ced53f1dd to your computer and use it in GitHub Desktop.
How to use FIND and SED together

Combining both find and sed to find and replace words

Example script

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, and spec directories
  • it only looks at file types that are either .rb or .sql files
  • it replaces the word dollar_value with the word budget_value

Broken down into pieces

find

The start of the find command


app db spec

These are the directories to look in from your current location. You could replace this with ./ to look in ANY directory


-type f

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.


\( -name '*.rb' -o -name '*.sql' \)

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 the OR 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

-exec <script> {} \;

This tells find that we we should like to execute a script on each result the find command returns.


sed

This is the start of the sed command


-i ''

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.


-e <parameter>

Tell sed that we are giving it a regular expression we should like it to evaluate


's/<word_to_replace>/<what_to_replace_it_with>/g'

Regular expression. Find this, replace with this. /g means replace all occurances on a line, rather than just the first.


Second Example

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 word budget_value, but only the first occurance on a line
  • makes a copy of the files before it changes with a .bak extension
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment