将输出从 sed 's/c/d/' myFile 重定向到 myFile [英] Redirect output from sed 's/c/d/' myFile to myFile

查看:26
本文介绍了将输出从 sed 's/c/d/' myFile 重定向到 myFile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在脚本中使用 sed 进行替换,我想让替换的文件覆盖该文件.通常我认为你会使用这个:

I am using sed in a script to do a replace and I want to have the replaced file overwrite the file. Normally I think that you would use this:

% sed -i 's/cat/dog/' manipulate
sed: illegal option -- i

但是正如你所看到的,我的 sed 没有那个命令.

However as you can see my sed does not have that command.

我试过了:

% sed 's/cat/dog/' manipulate > manipulate

但这只是将操作变成了一个空文件(有道理).

But this just turns manipulate into an empty file (makes sense).

这有效:

% sed 's/cat/dog/' manipulate > tmp; mv tmp manipulate

但我想知道是否有一种标准方法可以将输出重定向到与输入相同的文件中.

But I was wondering if there was a standard way to redirect output into the same file that input was taken from.

推荐答案

我通常使用第三种方式,但有一个重要变化:

I commonly use the 3rd way, but with an important change:

$ sed 's/cat/dog/' 操作 >tmp &&mv tmp 操作

即将 ; 更改为 && 以便移动仅在 sed 成功时发生;否则,一旦您在 sed 语法中打错字,您就会丢失原始文件.

I.e. change ; to && so the move only happens if sed is successful; otherwise you'll lose your original file as soon as you make a typo in your sed syntax.

注意!对于那些阅读标题并错过 OP 约束的人我的 sed 不支持 -i":对于大多数人, sed 将支持 -i,因此最好的方法是:

Note! For those reading the title and missing the OP's constraint "my sed doesn't support -i": For most people, sed will support -i, so the best way to do this is:

$ sed -i 's/cat/dog/' 操作

这篇关于将输出从 sed 's/c/d/' myFile 重定向到 myFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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