IT

Replace all instances of a string in a file

How to Replace all instances of a string in a file?

  1. Open the file in read mode using the open() function.
  2. Read the contents of the file into a string using the read() method.
  3. Use the replace() method to replace all instances of the target string with the new string.
  4. Open the file in write mode using the open() function.
  5. Write the modified string to the file using the write() method.
  6. Close the file using the close() method.

Here is an example code snippet:

How to Replace all instances of a string in a file?

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 hat

  • On Windows or Linux using Perl

    perl -pi.orig -e “s///g;”

  • On Windows or Linux using Python

Source:

  1. http://stackoverflow.com/questions/60034/how-can-you-find-and-replace-text-in-a-file-using-the-windows-command-line-envir
Etienne Noumen

Sports Lover, Linux guru, Engineer, Entrepreneur & Family Man.

Recent Posts

A Daily Chronicle of AI Innovations in May 2024

AI Innovations in May 2024

19 hours ago

Tips for Ensuring Success Throughout Your Career

For most people, a satisfactory career is essential for leading a happy life. However, ensuring…

5 days ago

Different Career Paths in the Pipeline Industry

The pipeline industry is more than pipework and construction, and we explore those details in…

5 days ago

SQL Interview Questions and Answers

SQL Interview Questions and Answers In the world of data-driven decision-making, SQL (Structured Query Language)…

2 weeks ago

Things To Consider When Switching Internet Providers

Before you make the decision to switch your home’s interest service provider, take the time…

4 weeks ago

A Daily Chronicle of AI Innovations in April 2024

AI Innovations in April 2024. Welcome to the April 2024 edition of the Daily Chronicle,…

1 month ago