Which Unix/Linux command sorts the lines of a file in reverse (descending) order directly from the command line?

Difficulty: Easy

Correct Answer: sort -r

Explanation:


Introduction / Context:
Sorting text data is fundamental in log analysis, report generation, and data cleaning. The standard 'sort' utility can order lines lexicographically or numerically, and supports reversing the order with a simple switch for quick, scriptable transformations.


Given Data / Assumptions:

  • You have a text file whose lines need reverse ordering.
  • Default collation is acceptable (or you will add keys/switches).
  • You want a one-liner solution.


Concept / Approach:
'sort -r file' outputs the same lines in descending order. Combine with '-n' for numeric reverse order ('sort -nr'), or specify keys with '-k' for column-based sorts. Piping from another command is common in Unix pipelines to reverse-stream data on the fly.


Step-by-Step Solution:

Reverse lexicographic: sort -r data.txtReverse numeric by column 3: sort -k3,3nr data.txtReverse stdin: cmd | sort -rWrite to file: sort -r data.txt > reversed.txt


Verification / Alternative check:
Compare 'sort file' vs 'sort -r file' outputs to confirm reversed ordering. For numbers, add '-n' and verify correct numeric treatment rather than string ordering.


Why Other Options Are Wrong:

  • sort: Sorts ascending by default, not reverse.
  • sh / st: Not sorting commands.
  • None of the above: Incorrect because 'sort -r' is correct.


Common Pitfalls:
Forgetting '-n' for numeric data, locale-collation surprises, or neglecting '-k' when sorting on specific fields.


Final Answer:
sort -r

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion