Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python one-liner to replace one word with another word in text file

Tags:

python

I'm trying to use Python (through a Linux terminal) to replace the word 'example' in following line of a text file text_file.txt:

abcdefgh example uvwxyz

What I want is:

abcdefgh replaced_example uvwxyz

Can I do this with a one-liner in Python?

EDIT: I have a perl one-liner perl -p -i -e 's#example#replaced_example#' text_file.txt but I want to do it in Python too

like image 479
prrao Avatar asked Jan 23 '26 09:01

prrao


1 Answers

You can do it:

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

But it's rather clunky. Python's syntax isn't designed to make nice 1-liners (although frequently it works out that way). Python values clarity above everything else which is one reason you need to import things to get the real powerful tools python has to offer. Since you need to import things to really leverage the power of python, it doesn't lend to creating simple scripts from the commandline.

I would rather use a tool that is designed for this sort of thing -- e.g. sed:

sed -e 's/example/replace_example/g' text_file.txt
like image 108
mgilson Avatar answered Jan 25 '26 22:01

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!