Next Spaceship

Driving into future...

Replace All Strings in a File

Here is the script to replace all strings in a file.

python Replace Strings In A File #!/usr/bin/python #Created by Leon import os, glob, re old = "oldfile" new = "newfile" fin1 = open(old) fout = open(newfile, "w") data = fin1.readlines() for line in data: fout.write(line) m ="some string", line) if m: print fout.write("some new strings") fin1.close() fout.close()

You can also use the sed command:


As on some system, sed is at a very old version, and some useful characters cannot be recognized. In this case, you can use Perl as an alternative:

perl -e '($_ = join "",<>) =~ s/OLD_STR/NEW_STR/g; print;' OLD_FILE > NEW_FILE