Member Avatar for Member #1128301

How do I sort a text file which has been listed already by size order, then take that list and put it into reverse alphabetical order?

Dani AI

Generated

If your file is already in the form "SIZE NAME" (size first, then filename), tell sort which field to use instead of re-sorting the whole line. Building on ’s pointer to sort and ’s note about avoiding UUOC, here are the two common cases.

Reverse alphabetical by the name column (ignoring the size column):

sort -k2,2r input.txt > output.txt

Keep size as primary and only reverse-alphabetize names within equal sizes:

sort -nrk1,1 -k2,2r input.txt > output.txt

If the size values have human-readable units (from du -h or ls -lh), use -h:

sort -hk1,1 -k2,2r input.txt > output.txt

Practical tips:

  • Locale can change sort order; for bytewise ASCII order use: LC_ALL=C sort ....
  • If your input is an ls -l listing, filenames usually start at field 9, so you might use sort -k9,9r. That said, ls output is brittle with spaces/symlinks. Prefer generating a clean, tab-delimited list and then sorting:
find . -maxdepth 1 -type f -printf '%s\t%f\n' | sort -nrk1,1 -k2,2r

These patterns let you precisely control whether you are simply reverse-alphabetizing by name, or keeping the original size ordering while using the name as a tie-breaker.

Recommended Answers

All 3 Replies

How about

sort -r

commented: sort -r only sorts the directory, I want to sort the text file +0

@MarkQ97
If I want to sort a file I can do this with a pipe.
cat file | sort -r > newfile

The sort flags are picked as you wish and my crude example is just that.

Your reply about a directory seems odd but I take it you need a reminder of Linux command lines. One can also not pipe but redirect like:
sort -r < file > newfile

And for more fun you can get the last so many lines with tail then sort like:
tail file|sort -r > newfil

Isn't it an example of UUOC ? It seems to me that sort -r -o newfile file should work.

commented: Some folk need to see more examples. even sort -r file.txt should work but they may be quite new to the command line. +6
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.