如何在Unix中应用具有相同输入和输出文件的sort和uniq?

How to apply sort and uniq having the same input and output file in Unix?

我想对两个或多个文本文件应用一些操作(交集和重聚) 所以在我将所有行放在一起之后,我必须对该文件应用排序和唯一性。 问题是我想要相同的输入和输出文件(-i 不起作用)。 这是我的代码:

  nr_param=$#
    case  in

    '-r')
        if [ "$nr_param" = 3 ]
        then
            echo "reuniunea"
            rm -f reuniune1.txt
            cat   >> reuniune1.txt
            sort <reuniune1.txt | uniq >reuniune.txt 
            rm -f reuniune1.txt
        else
            echo "parametri incorecti"
        fi;;
    '-i') 
        if [ "$nr_param" = 3 ]
        then
            echo "intersectia"
            rm -f intersectie.txt
            grep -Fx -f   > intersectie.txt
        else
            echo "parametri incorecti"
        fi;;

你能帮我在不使用额外文件的情况下做同样的事情吗? 如果 $2 为 "intersectie.txt".

,则 grep 相同

编辑 --

我在半睡半醒的时候写下了下面的内容,;-) 对于您的情况,这里有一个很好的捷径

  sort -u -o file file

-u 选项使排序后的数据具有唯一性,如下所述,-o file 会将输出保存到您指定的任何文件中,包括与输入同名的文件。

如果你想做类似的事情

  sort < file | uniq -c > uniqFileWithCounts

那么第一个想法对你没有帮助。


不要自欺欺人,即使您使用 sort -o file file 为排序的 -o(utput) 重用相同的文件名,在后台系统也必须将所有数据写入一个 tmp 文件,然后重命名为 -o file 指定的文件(同时 sort 正在将中间排序数据写入 /tmp 目录,并在最终输出完成时将其删除)。

所以你最好的选择是

sort <reuniune1.txt | uniq > uniqd.txt && mv uniqd.txt reuniune1.txt 

如果 sort | uniq 进程没有错误退出,这只会覆盖 reuniune1.txt。

IHTH