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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6484340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:42:41  来源:igfitidea点击:

Text substitution (reading from file and saving to the same file) on linux with sed

bashunixsedcommand-line-interface

提问by Roger

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

我想读取文件“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...

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

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

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

or:

或者:

$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.htmlhere's my updated code:

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

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

回答by geekosaur

On Linux, sed -iis the way to go. sedisn'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.

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

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

得到空文件的原因是 shell 在运行命令之前打开(并截断)了该文件。

回答by Antti

You want: sed -i 's/foo/bar/g' file

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

回答by Scott C Wilson

You want to use "sed -i". This updates in place.

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

回答by Gjorgji Tashkovski

In-place editing with perl

使用 perl 进行就地编辑

perl -pi -w -e 's/foo/bar/g;' file.txt

or

或者

perl -pi -w -e 's/foo/bar/g;' files*

for many files

对于许多文件

回答by glenn Hymanman

The edsolution is:

ed解决方案是:

ed teste <<END
1,$s/find/replace/g
w
q
END

Or without the heredoc

或者没有heredoc

printf "%s\n" '1,$s/find/replace/g' w q | ed teste

回答by limtete

Actually, if you use -iflag, sedwill copy the original line you edit.

实际上,如果您使用-i标志,sed将复制您编辑的原始行。

So this might be a better way:

所以这可能是一个更好的方法:

sed -i -e 's/old/new/g' -e '/new/d' file