如何执行任何使用bash编辑其文件(自变量)的命令(自变量)?

时间:2020-03-06 14:51:00  来源:igfitidea点击:

我有一个文件temp.txt,我想用bash中的sort命令排序。

我希望排序后的结果替换原始文件。

例如,这不起作用(我得到一个空文件):

sortx temp.txt > temp.txt

可以在一行中完成此操作而无需复制到临时文件吗?

编辑:-o选项对于sort很酷。我在问题中以sort为例。我在其他命令中遇到了同样的问题:

uniq temp.txt > temp.txt.

有更好的一般解决方案吗?

解决方案

在非交互式编辑器" ex"上阅读。

在这里,一行:

sort temp.txt > temp.txt.sort && mv temp.txt.sort temp.txt

从技术上讲,不会复制到临时文件,并且" mv"命令应该是即时的。

sort temp.txt -o temp.txt

使用参数--output =或者-o

刚刚在FreeBSD上尝试过:

sort temp.txt -otemp.txt

如果我们坚持使用sort程序,则必须使用中间文件-我不认为sort具有在内存中排序的选项。除非我们可以保证stdin / stdout的stdin的缓冲区大小足以容纳整个文件,否则其他任何技巧都将失败。

编辑:对我感到羞耻。 sort temp.txt -o temp.txt效果很好。

许多人提到了-o选项。这是手册页部分。

从手册页:

-o output-file
          Write output to output-file instead of to the  standard  output.
          If  output-file  is  one of the input files, sort copies it to a
          temporary file before sorting and writing the output to  output-
          file.

" sort"需要先查看所有输入,然后才能开始输出。由于这个原因,sort程序可以很容易地提供一个就地修改文件的选项:

sort temp.txt -o temp.txt

具体来说,GNUsort的文档说:

Normally, sort reads all input before opening output-file, so you can safely sort a file in place by using commands like sort -o F F and cat F | sort -o F. However, sort with --merge (-m) can open the output file before reading all input, so a command like cat F | sort -m -o F - G is not safe as sort might start writing F before cat is done reading it.

虽然BSDsort的文档中说:

If [the] output-file  is one of the input files, sort copies it to a temporary file before sorting and writing the output to [the] output-file.

诸如" uniq"之类的命令可以在完成读取输入之前开始写入输出。这些命令通常不支持就地编辑(使它们难以支持此功能)。

通常,我们可以使用一个临时文件来解决此问题,或者如果我们绝对希望避免使用中间文件,则可以在写出缓冲区之前使用缓冲区存储完整的结果。例如,使用perl

uniq temp.txt | perl -e 'undef $/; $_ = <>; open(OUT,">temp.txt"); print OUT;'

在这里,perl部分从变量" $ _"中读取" uniq"的完整输出,然后用该数据覆盖原始文件。我们可以使用自己选择的脚本语言执行相同的操作,甚至在Bash中也可以。但是请注意,它将需要足够的内存来存储整个文件,在处理大文件时不建议这样做。

这将受到高度的内存限制,但是我们可以使用awk将中间数据存储在内存中,然后将其写回。

uniq temp.txt | awk '{line[i++] = 
sort inputfile | uniq | sort -o inputfile
}END{for(j=0;j<i;j++){print line[j]}}' > temp.txt

要添加uniq功能,不利之处在于:

{ rm file && uniq > file; } < file

这是更通用的方法,可与uniq,sort和whatnot一起使用。

##代码##