Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I can use sed to do recursively find and replace a string in a bunch of files. Like so:

find -name  "*.py"  -not \( -name .svn -prune \) -type f -print0  | xargs
-0  sed -i 's/cat/dog/g'

However is there a way to search for a string both inside a file and in the actual file names?

If the string is found in the name of a file, then replace the string in the file name with a new string.

If the string inside the actual file, then replace the string with a new string.

And of course, to search recursively.

Any ideas?

share|improve this question

I don't know how to do this in one go, but it can easily be accomplished as a small script, e.g. (lightly tested):

find -name  "*.py"  -not \( -name .svn -prune \) -type f -print0 \
| while read -r -d $'\0' filename; do
    sed -i 's/cat/dog/g' "$filename"
    echo "$filename" | grep -q "cat" \
    && mv "$filename" "${filename/cat/dog}"
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.