如何删除文件中的重复行?
我知道一般方法是使用类似的方法
$ sort file1.txt | uniq > file2.txt
,但我想知道是否有一种方法可以在不需要单独的源和目标文件的情况下进行此操作,即使这意味着它不能是单线。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我知道一般方法是使用类似的方法
$ sort file1.txt | uniq > file2.txt
,但我想知道是否有一种方法可以在不需要单独的源和目标文件的情况下进行此操作,即使这意味着它不能是单线。
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
只需使用
-O
和-U
sort> sort
的选项:您甚至不需要将管道用于另一个命令,例如<代码> uniq 。
Simply use the
-o
and-u
options ofsort
:You don't need even to use a pipe for another command, such as
uniq
.使用GNU AWK进行“ Inplace”编辑:
与所有工具一样(
ED
,要求首先读取整个文件)支持“ Intherplope”编辑(sed -i ,
perl -i
,ruby -i
等)这使用了场景后面的临时文件。对于任何尴尬,您可以在没有使用的温度文件的情况下进行以下操作,但大约是使用的内存的两倍:
With GNU awk for "inplace" editing:
As with all tools (except
ed
which requires the whole file to be read into memory first) that support "inplace" editing (sed -i
,perl -i
,ruby -i
, etc.) this uses a temp file behind the scenes.With any awk you can do the following with no temp files used but about twice the memory used instead:
使用Perl的
-i
:-i
更改文件“适当”;-n
按行读取输入,为每行的代码运行;-l </code>从输入中删除新线,并将它们添加到
print
;With Perl's
-i
:-i
changes the file "in place";-n
reads the input line by line, running the code for each line;-l
removes newlines from input and adds them toprint
;%seen
hash idiom is described in perlfaq4.一个常见的成语是:
&amp;&amp;
很重要:如果管道失败,那么原始文件就不会被(也许)垃圾覆盖。Linux
moreutils
包包含一个将其封装的程序:A common idiom is:
The
&&
is important: if the pipeline fails, then the original file won't be overwritten with (perhaps) garbage.The Linux
moreutils
package contains a program that encapsulates this away: