Skip to content
Advertisement

Using linux sort on multiple files

Is there a way I can run the following command with Linux for many files at once?

$ sort -nr -k 2 file1 > file2

Advertisement

Answer

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. 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”:

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
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement