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 want to replace text string in any type file(for example perl,cgi,text,binary,js and ...) in multiple folder in linux.

How do i do?


share|improve this question
You will need to provide a little more background information before your requirements are really clear. For example, do you want to do this text replacement in a script, or would an editor be OK? Since the example files can all be classified as text or binary, do you need a method which works with text and binary? What have you tried, so far? – pavium Dec 23 '09 at 8:52
I want to replace test string at about 500 files so i need script. I need a method which works with text, binary, perl, cgi and ... Tank's for answer – M.Rezaei Dec 23 '09 at 10:23

The problem with editing binary files is that they are often laid out in a particular format with the position of particular bytes having significance. So trying to automate that can be very difficult and should probably be done with a tool that understands the format of the file.

The following Bash script can be used to edit text files:

while read -r file
    tempfile=$(tempfile) || tempfile=$(mktemp) || { tempfile="/tmp/tmpfile.$$" && touch "$tempfile"; } &&
    sed 's/original text/new text/g' "$file" > "$tempfile" &&
    mv "$tempfile" "$file"
    } || echo "Edit failed for $file"
done < <(find . -type f)

or change the second and last lines to:

find . -type f | while



If your version of sed can do in-place editing, then you can eliminate the creation of temporary files (everything between do and done above) and use this sed command inside the loop instead:

sed -i 's/original text/new text/g' "$file"
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.