使用sed在linux上进行文本替换(从文件读取并保存到同一文件)

Rog*_*ger 16 unix bash sed command-line-interface

我想阅读文件"teste",做一些"查找和替换"并用结果覆盖"teste".我到现在越接近:

$cat teste
I have to find something
This is hard to find...
Find it wright now!

$sed -n 's/find/replace/w teste1' teste

$cat teste1
I have to replace something
This is hard to replace...
Run Code Online (Sandbox Code Playgroud)

如果我尝试像这样保存到同一个文件:

$sed -n 's/find/replace/w teste' teste
Run Code Online (Sandbox Code Playgroud)

要么:

$sed -n 's/find/replace/' teste > teste
Run Code Online (Sandbox Code Playgroud)

结果将是一个空白文件...

我知道我错过了一些非常愚蠢的东西,但欢迎任何帮助.


更新:根据人们提供的提示和这个链接:http://idolinux.blogspot.com/2008/08/sed-in-place-edit.html这里是我的更新代码:

sed -i -e 's/find/replace/g' teste 
Run Code Online (Sandbox Code Playgroud)

gee*_*aur 26

在Linux上,sed -i是要走的路. sed但实际上并不是为就地编辑而设计的; 从历史上看,它是一个过滤器,一个编辑管道中数据流的程序,对于这种用法,您需要写入临时文件然后重命名它.

获得空文件的原因是shell在运行命令之前打开(并截断)文件.


Ant*_*tti 9

你要: sed -i 's/foo/bar/g' file

  • 就我而言,我需要表达式的 -e 前缀 (2认同)

Sco*_*son 8

您想使用“sed -i”。这更新到位。