How to search directory for specific files?

In Unix, how do I do a recursive search and replace on a batch of files in a given directory?

  • Answer:

    find <directory> -type f -exec sed -i 's/original/changed/g' {} \;

Parimal Gaikwad at Quora Visit the source

Was this solution helpful to you?

Other answers

I think this is a simple application of "for loop" in shel script.

Naveen Jain

The traditional answer is the one already given with find and sed. This replaces "foo" with "bar" in all text files: find . -name '*.txt' -print -exec sed -i.bak 's/foo/bar/g' {} \; (Equivalently, you can use "perl -pi -e s/foo/bar/g" instead of sed.) However, for common scenarios, you may find the command http://manpages.ubuntu.com/manpages/trusty/man1/rpl.1.html is easier to remember. Here is replacement on all files, recursively, in the current directory: rpl -R foo bar . It's not available by default on some Linux or Unix installations but is quick to install ("apt-get install rpl" on Ubuntu, for example). For tougher jobs with more complex renaming or changing of file contents or filenames, the most powerful tool I'm aware of is https://github.com/jlevy/repren, a small Python script I wrote a while back for some thornier renaming and refactoring tasks. The situations where you might prefer it include: Renaming and moving of files and directories as well as search and replace on file contents (my-dir/foo-stuff/foo.txt -> my-dir/bar-stuff/bar.txt). See a "dry run" of changes before you commit to performing the search and replace. Support regular expressions with back substitution, whole words, case insensitive, and case preserving (foo -> bar, Foo -> Bar, FOO -> BAR) modes. Multiple simultaneous replacements, including swaps (foo -> bar and bar -> foo, without an intermediate rename) or sets of non-unique replacements (foo -> bar, f -> x). Check the repren page for details.

Joshua Levy

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.