简体   繁体   English

使用linux对多个文件进行排序

[英]Using linux sort on multiple files

有没有一种方法可以在Linux上一次对许多文件运行以下命令?

$ sort -nr -k 2 file1 > file2

I assume you have many input files, and you want to create a sorted version of each of them. 我假设您有许多输入文件,并且要为每个文件创建一个排序的版本。 I would do this using something like 我会使用类似的方法

for f in file*
do
    sort $f > $f.sort
done

Now, this has the small problem that if you run it again, if will not only sort all the files again, it will also create file1.sort.sort to go with file1.sort. 现在,这有一个小问题:如果再次运行它,不仅将再次对所有文件进行排序,还将创建file1.sort.sort与file1.sort一起使用。 There are various ways to fix that. 有多种解决方法。 We can fix the second problem by creating sorted files thate don't have names beginning with "file": 我们可以通过创建没有名称以“ file”开头的排序文件来解决第二个问题:

for f in file*
do
    sort $f > sorted.$f
done

But that's kind of weird, and I wouldn't want files named like that. 但这有点奇怪,我也不想这样命名的文件。 Alternatively, we could use a slightly more clever script that checks whether the file needs sorting, and avoids both problems: 或者,我们可以使用稍微更聪明的脚本来检查文件是否需要排序,并避免两个问题:

for f in file*
do
    if expr $f : '.*\.sort' > /dev/null
    then
        : no need to sort
    elif test -e $f.sort
    then
        : already sorted
    else
        sort -nr -k 2 $f > $f.sort
    fi
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM