How to Replace all instances of a string in a file?
- Open the file in read mode using the
open()
function. - Read the contents of the file into a string using the
read()
method. - Use the
replace()
method to replace all instances of the target string with the new string. - Open the file in write mode using the
open()
function. - Write the modified string to the file using the
write()
method. - Close the file using the
close()
method.
Here is an example code snippet:

This will replace all instances of old_string
with new_string
in the file file.txt
.
# Open the file in read mode
with open(‘file.txt’, ‘r’) as f:
# Read the contents of the file into a string
contents = f.read()
# Replace all instances of the target string
contents = contents.replace(‘old_string’, ‘new_string’)
# Open the file in write mode
with open(‘file.txt’, ‘w’) as f:
# Write the modified string to the file
f.write(contents)
# Close the file
f.close()
Shell script to replace all instances of a string in a file on Linux & Windows.
On Linux via bash script
sed “s/$stringToReplace/$replaceWith/g” $File_Name > $File_Name
On Windows using Powershell
( get-content $File_Name ) | % { $_ -replace $stringToReplace, $replaceWith } | set-content $File_Name
On Windows using Batch
set str=teh cat in teh hat
echo.%str%
set str=%str:teh=the%
echo.%str%Script Output:
teh cat in teh hat
the cat in the hatOn Windows or Linux using Perl
perl -pi.orig -e “s///g;”
On Windows or Linux using Python
Source: