如何将输入和输出作为同一个文件运行 sed 命令? [英] How do I run the sed command with input and output as the same file?

查看:51
本文介绍了如何将输入和输出作为同一个文件运行 sed 命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 shell 脚本中使用 sed 命令,我想在其中删除读取 STARTremoveThisComment 的行和读取 removeThisCommentEND 的行.

I'm trying to do use the sed command in a shell script where I want to remove lines that read STARTremoveThisComment and lines that read removeThisCommentEND.

当我使用

sed 's/STARTremoveThisComment//' > test

但是我如何通过使用相同的文件作为输入和输出来做到这一点?

But how do I do this by using the same file as input and output?

推荐答案

sed -i(或扩展版本,--in-place)将自动化该过程通常使用不太先进的实现来完成,即将输出发送到临时文件,然后将其重命名回原始文件.

sed -i (or the extended version, --in-place) will automate the process normally done with less advanced implementations, that of sending output to temporary file, then renaming that back to the original.

-i 用于就地编辑,您还可以提供备份后缀以保留原始副本:

The -i is for in-place editing, and you can also provide a backup suffix for keeping a copy of the original:

sed -i.bak fileToChange
sed --in-place=.bak fileToChange

两者都将原始文件保存在 fileToChange.bak 中.

Both of those will keep the original file in fileToChange.bak.

请记住,就地编辑可能不适用于所有 sed 实现,但 在 GNU sed 中应该可用在所有 Linux 变体上,根据您的标签.

Keep in mind that in-place editing may not be available in all sed implementations but it is in GNU sed which should be available on all variants of Linux, as per your tags.

如果您使用的是更原始的实现,则可以使用以下内容:

If you're using a more primitive implementation, you can use something like:

cp oldfile oldfile.bak && sed 'whatever' oldfile >newfile && mv newfile oldfile

这篇关于如何将输入和输出作为同一个文件运行 sed 命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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