[Python One-Liners] How to Replace a String in a File From Your Terminal?

Rate this post

Problem: You use Python in a terminal and you want to replace a string 'example' in a text file file.txt:

xxxxx example xxxxx

Your goal is to accomplish the following text:

xxxxx replaced_example xxxxx

In particular, you want to open the file, replace the text, and rewrite the result into the file—all in a single line of Python code!

Can a Python one-liner accomplish this?

Answer: Yes! You can compress any Python script into a single line. For computer science nerds: the single line of Python code is Turing complete.

Let’s see how you can accomplish this task as a Python one-liner!

Method 1: Print to Standard Input

The first method is best if you want to replace all occurrences of "example" with "replaced_example" and print the result to the standard input.

python -c "print(open('file.txt').read().replace('example','replaced_example'))"

The replace method replaces all occurrences of the first argument with the second argument. It returns the new string. You can now print the result to the stdin or write it back to a file.

Method 2: Print to File

The second method is best if you want to replace all occurrences of "example" with "replaced_example" and write the result to a new file "file2.txt".

python -c "print(open('file.txt').read().replace('example','replaced_example'), file=open('file2.txt', 'w'))"

The replace method replaces all occurrences of the first argument with the second argument. It returns the new string. You can now print the result to the file with means of the file argument of the print function.

Method 3: exec()

You can always convert a multi-liner into a one-liner using the exec() function. Say, you have the following multiline script to replace all occurrences of a string in a file:

with open('file.txt', 'r') as f:
    s = f.read().replace('example', 'replaced_example')
with open('file.txt', 'w') as f:
    f.write(s)

You first open the file in read mode reading all its contents and creating the new string with replaced occurrences of the string 'example'. After that, you open the file in writing mode to overwrite its contents.

You use the exec() function to one-linerize this script:

exec("with open('file.txt', 'r') as f:\n    s = f.read().replace('example', 'replaced_example')\nwith open('file.txt', 'w') as f:\n    f.write(s)")

All you did is to replace the new lines with the new line character \n. This resulting script is a not-so-concise one-liner to replace all contents of a given file!

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!