如何在不删除文件的情况下重定向cat myfile>我的档案 [英] How to redirect without erasing file cat myfile > myfile
问题描述
我对不删除文件重定向到文件的正确方法有疑问? 我正在使用bash.我想做类似的事情:
I have a question about what is the right way to redirect to a file without erasing the file? I'm using bash. I would like to do something like:
cat myfile > myfile
程序(即cat)读取文件然后重定向到文件的位置,因此在上面的示例中,"myfile"将保持不变.
where the program (i.e. cat) reads the file and then redirects to the file, so in the example above 'myfile' would be unchanged.
我知道上面的示例将删除文件在这里解释.
I know that the example above will erase the file, as explained here.
什么是正确的语法,这样就不会删除文件?是否可以进行stdout和重定向,或者程序应处理打开新数据并将新数据写入文件的操作?我想让我的程序只输出到stdout,然后用户可以重定向或管道或其他任何内容.
What is the proper syntax so the file won't be erased? Is stdout and redirection possible, or should the program handle opening and writing the new data to the file? I would like to let my program just output to stdout and then the user can redirect or pipe or whatever.
顺便说一句,我不想>>和连接.我希望左侧的函数将新"数据写入文件.
BTW, I don't want to >> and concatenate. I want the function on the left to write "new" data to the file.
也许更好的说法是,我希望重定向的左侧在流式传输发生之前完全发生,这可能吗?如果我对bash有基本的误解,请告诉我:-)
Perhaps a better way to state it is that I want the left side of the redirection to fully occur before the streaming occurs, is this possible? If I have a fundamental misunderstanding of bash here, please enlighten me :-)
推荐答案
您必须先将所有数据读取到内存中,或者写入一个临时文件并将其换出.
You have to either read all the data to memory first, or write to a temporary file and swap it out.
要将其读入内存(如vim
,ed
和其他编辑器一样):
To read it into memory (like vim
, ed
and other editors do):
contents=$(<myfile)
cat <<< "$contents" > myfile
要创建一个临时文件(例如sed -i
,rsync
和其他更新工具):
To create a temporary file (like sed -i
, rsync
and other updating tools do):
tmpfile=$(mktemp fooXXXXXX)
cat myfile > "$tmpfile" && mv "$tmpfile" myfile
这篇关于如何在不删除文件的情况下重定向cat myfile>我的档案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!