1

In Mac OS, how do I find and replace a certain text in all of a directory and its sub directories?

1
  • file/directory names are contents? May 28, 2010 at 18:07

1 Answer 1

5

Use a combination of find(1) and sed(1):

# Find all files under the directory hierarchy rooted at 'root', and replace
# all instances of the regular expression 'pattern' with 'replacement' in all
# of those files:
find root -type f -exec sed -i~ 's/pattern/replacement/g' '{}' '+'

If you run into command line length limitations, replace the '+' at the end with ';'. This will make it run slower (since it was to fork a new process for each file), but it will not have a danger of too long of a command line for sed.

You can also only do the replacement for certain files by adding appropriate filters to find (e.g. -name *.txt to only replace .txt files).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .