Sorting text on UNIX/Linux Which command sorts the lines of a file in reverse (descending) order when run from the shell?
-
Asort -r
-
Bst
-
Csh
-
Dsort
-
ENone of the above
Answer
Correct Answer: sort -r
Explanation
Introduction / Context:Sorting text files is a routine administrative task. The standard utility on UNIX/Linux is sort, which supports many options for collation, numeric comparison, and order direction. Knowing the correct flag for reverse order prevents manual post-processing and simplifies pipelines.
Given Data / Assumptions:
- We want reverse (descending) order.
- We will use the standard command-line tool set.
- Default collation is acceptable unless otherwise specified.
Concept / Approach:The sort utility orders input lines. By default it sorts ascending. The option -r reverses the result, producing descending order. Other flags such as -n (numeric) or -k (key) can be combined depending on the data set.
Step-by-Step Solution:Use ascending by default: sort file.txt.Add reverse flag: sort -r file.txt for descending order.Combine with numeric if needed: sort -nr file.txt for descending numeric sort.Integrate into pipelines: cat file.txt | sort -r > out.txt.
Verification / Alternative check:Test with a known sequence (e.g., 1, 2, 3) and confirm output (3, 2, 1). Use LC_ALL=C to provide bytewise collation for reproducibility in scripts.
Why Other Options Are Wrong:st and sh are unrelated; sh invokes a shell, not sorting.sort (without -r) sorts ascending; not reverse order.
Common Pitfalls:
- Forgetting -n for numeric data, which causes 100 to sort before 20 lexically.
- Not setting locale when deterministic order is required across systems.
- Sorting by the wrong key when dealing with multi-column data; use -k properly.
Final Answer:sort -r