我想读取文件“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...
如果我尝试像这样保存到同一个文件:
$sed -n 's/find/replace/w teste' teste
或:
$sed -n 's/find/replace/' teste > teste
结果将是一个空白文件...
我知道我遗漏了一些非常愚蠢的东西,但欢迎任何帮助。
更新:根据人们提供的提示和此链接:http://idolinux.blogspot.com/2008/08/sed-in-place-edit.html这是我更新的代码:
sed -i -e 's/find/replace/g' teste
最佳答案
在 Linux 上,sed -i
是可行的方法。不过,sed
实际上并不是为就地编辑而设计的;从历史上看,它是一个过滤器,一个在管道中编辑数据流的程序,对于这种用法,您需要写入一个临时文件,然后重命名它。
你得到一个空文件的原因是 shell 在运行命令之前打开(并截断)了文件。
关于bash - 使用 sed 在 linux 上进行文本替换(从文件读取并保存到同一文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6484340/