我试图使用Python (通过Linux终端)替换文本文件text_file.txt下面一行中的“示例”一词
abcdefgh example uvwxyz我想要的是:
abcdefgh replaced_example uvwxyz我可以用Python中的一行代码来完成这个任务吗?
编辑:,我有一个perl单行perl -p -i -e 's#example#replaced_example#' text_file.txt,但是我也想用进行编辑。
发布于 2012-10-17 18:57:16
你可以这样做:
python -c 'print open("text_file.txt").read().replace("example","replaced_example")'但它相当笨重。Python的语法并不是设计成好的1行(虽然它经常是这样的)。Python比其他任何东西都更重视清晰度,这也是您需要导入东西才能获得python必须提供的真正强大工具的原因之一。因为您需要导入东西才能真正利用python的功能,所以它不适合从命令行创建简单的脚本。
我宁愿使用为这类事情而设计的工具,例如sed。
sed -e 's/example/replace_example/g' text_file.txt发布于 2012-10-17 19:12:48
顺便提一句,文件输入模块支持内部修改,就像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"),
'https://stackoverflow.com/questions/12941091
复制相似问题