Linux – How to replace text string in any type file(for example binary and …) and multiple files in linux

linuxsearch-and-replacestrings

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.

Best Answer

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"