As an easy example, consider the following command:

作为一个简单的例子,考虑以下命令:

$ sort file.txt 

This will output the file's data in sorted order. How do I put that data right back into the same file? I want to update the file with the sorted results.

这将按顺序输出文件的数据。如何将这些数据返回到同一个文件中呢?我想用排序后的结果更新文件。

This is not the solution:

这不是解决办法:

$ sort file.txt > file.txt

... as it will cause the file to come out blank. Is there a way to update this file without creating a temporary file?

…因为它会导致文件为空。有没有一种方法可以在不创建临时文件的情况下更新这个文件?

Sure, I could do something like this:

当然,我可以这样做:

sort file.txt > temp.txt; mv temp.txt file.txt 

But I would rather keep the results in memory until processing is done, and then write them back to the same file. sort actually has a flag that will allow this to be possible:

但我宁愿将结果保存在内存中,直到处理完成,然后将它们写回相同的文件。sort实际上有一个标记,可以让它成为可能:

sort file.txt -o file.txt

...but I'm looking for a solution that doesn't rely on the binary having a special flag to account for this, as not all are guaranteed to. Is there some kind of linux command that will hold the data until the processing is finished?

…但我正在寻找一种解决方案,它不依赖于二进制文件有一个特殊的标志来说明这一点,因为并不是所有的二进制文件都保证这样做。是否有某种linux命令可以保存数据直到处理完成?

3 个解决方案

#1


1

For sort, you can use the -o option.

对于排序,可以使用-o选项。

For a more general solution, you can use sponge, from the moreutils package:

对于更一般的解决方案,你可以使用海绵,从moreutils包装:

sort file.txt | sponge file.txt

As mentioned below, error handling here is tricky. You may end up with an empty file if something goes wrong in the steps before sponge.

正如下面提到的,这里的错误处理很棘手。如果在使用海绵之前的步骤中出现问题,您可能会得到一个空文件。

This is a duplicate of this question, which discusses the solutions above: How do I execute any command editing its file (argument) "in place" using bash?

这是这个问题的副本,它讨论了上面的解决方案:如何执行任何命令编辑它的文件(参数)“到位”使用bash ?

更多相关文章

  1. linux中使用nfs共享文件
  2. Linux下文件同步、备份神器之-------rsync
  3. Linux利用i节点删除乱码文件
  4. debain 系统 ll 命令无法使用.目录和文件没有颜色区分解决之道
  5. 通过排除其父文件夹为多个目录创建单个tar文件
  6. find . -type f ! -name "*.o" 排除某类文件 排除多类文件 排除
  7. 来点基础的--诡异的极客们的符号--流、管道和文件的耦合
  8. Oracle:从SQL文件批量导入数据
  9. linux清空日志文件内容 比如log日志

随机推荐

  1. android代码片段一
  2. android SSL证书认证、SSL双向认证、http
  3. Android 获取设备唯一UUID
  4. Cordova插件编写流程(Android平台)
  5. android camera系统3A模式及其状态转换(二
  6. 【Android】如何寻找出某个Intent是否可
  7. Clickable URLs in Android TextViews
  8. android imageVIew拖动 && 图片缩放
  9. Android Manifest 用法
  10. Android HTTP请求