在Linux上使用sed进行文本替换(从文件读取并保存到同一文件) [英] Text substitution (reading from file and saving to the same file) on linux with sed

查看:45
本文介绍了在Linux上使用sed进行文本替换(从文件读取并保存到同一文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取文件"teste",进行一些查找和替换"并用结果覆盖"teste".我到现在为止的距离是:

I want to read the file "teste", make some "find&replace" and overwrite "teste" with the results. The closer i got till now is:

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

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

If I try to save to the same file like this:

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

或:

$sed -n 's/find/replace/' teste > teste

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

The result will be a blank file...

我知道我缺少一些非常愚蠢的东西,但是任何帮助都将受到欢迎.

I know I am missing something very stupid but any help will be welcome.

更新:基于人们给出的提示和此链接:

UPDATE: Based on the tips given by the folks and this link: http://idolinux.blogspot.com/2008/08/sed-in-place-edit.html here's my updated code:

sed -i -e 's/find/replace/g' teste 

推荐答案

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

On Linux, sed -i is the way to go. sed isn't actually designed for in-place editing, though; historically, it's a filter, a program which edits a stream of data in a pipeline, and for this usage you would need to write to a temporary file and then rename it.

得到一个空文件的原因是外壳程序在运行命令之前打开(并截断了)该文件.

The reason you get an empty file is that the shell opens (and truncates) the file before running the command.

这篇关于在Linux上使用sed进行文本替换(从文件读取并保存到同一文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆