简体   繁体   中英

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

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

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 -- eg sed :

sed -e 's/example/replace_example/g' text_file.txt

Incidentally the fileinput module supports inplace modification just like sed -i

-bash-3.2$ python -c '
import fileinput
for line in fileinput.input("text_file.txt", inplace=True):
    print line.replace("example","replace_example"),
'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM