为什么不“对文件1排序"文件1"工作? [英] Why doesn't "sort file1 > file1" work?
问题描述
当我尝试对文件进行排序并将排序后的输出保存在自身中时,就像这样
When I am trying to sort a file and save the sorted output in itself, like this
sort file1 > file1;
file1的内容将被完全删除,而当我尝试使用像这样的'tee'命令进行同样的操作
the contents of the file1 is getting erased altogether, whereas when i am trying to do the same with 'tee' command like this
sort file1 | tee file1;
它可以正常工作 [ed:仅对具有幸运时机的小型文件有效,会导致大型文件丢失或无用的进程调度而导致数据丢失] ,即它将覆盖已排序的输出file1本身,并在标准输出中显示它.
it works fine [ed: "works fine" only for small files with lucky timing, will cause lost data on large ones or with unhelpful process scheduling], i.e it is overwriting the sorted output of file1 in itself and also showing it on standard output.
有人可以解释为什么第一种情况不起作用吗?
Can someone explain why the first case is not working?
推荐答案
它不起作用,因为'>'重定向意味着会被截断,并且在将sort
的整个输出保留在内存中之前,请先将其重定向到在运行sort
之前,bash会截断文件并重定向输出.因此,file1
文件的内容将在sort
有机会阅读之前被截断.
It doesn't work because '>' redirection implies truncation, and to avoid keeping the whole output of sort
in the memory before re-directing to the file, bash truncates and redirects output before running sort
. Thus, contents of the file1
file will be truncated before sort
will have a chance to read it.
这篇关于为什么不“对文件1排序"文件1"工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!