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

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?

Tanks.

share|improve this question
1  
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

1 Answer 1

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:

#!/bin/bash
while read -r file
do
    {
    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

and

done

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

 
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.