2

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.

M.Rezaei
  • 405
  • 4
  • 9
  • 19
  • 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 08: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 Answers1

2

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"
Dennis Williamson
  • 60,515
  • 14
  • 113
  • 148