Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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
add comment

1 Answer 1

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}"
  done
share|improve this answer
add comment

Your Answer

 
discard

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.