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

标签 bash unix 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...

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

$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/

相关文章:

Python - 使用子进程调用 sed?

bash - 将 sed 或 awk 中的字符串大写

sql - 在 oracle 中插入和更新文件中的行

bash - -bash : sudo: No such file or directory

java - 如何使用 Netty 连接到 docker.sock?

c - C 中的 UNIX 共享内存和信号量

bash - bash(配置文件)中类似数组的数据结构?

运行 Bash 命令的 Python 脚本

linux - linux 中的子字符串基于第一次出现

json - awk 更改日期时间格式