On Unix/Linux, which command is used to sort the lines of a file in ascending (alphabetical/lexicographic) order?

Difficulty: Easy

Correct Answer: sort

Explanation:


Introduction / Context:
Sorting text is a common step in log analysis, report preparation, and data cleaning. The standard 'sort' utility orders lines lexicographically by default and can be tuned for numeric sorts, locale specifics, and key-based ordering, making it a versatile tool for shell pipelines and scripts.


Given Data / Assumptions:

  • You have a plain-text file containing multiple lines.
  • You want the default ascending ordering.
  • No special collation or key selection is required.


Concept / Approach:
Running 'sort filename' outputs lines in ascending order according to the system's locale. You can adjust behavior with options such as '-n' for numeric sort, '-k' to select sort keys, and '-r' for reverse order. Combining these options yields powerful one-liners for complex sorting tasks.


Step-by-Step Solution:

Alphabetical sort: sort input.txt > output.txtReverse order: sort -r input.txtNumeric sort on column 2: sort -k2,2n file.csvStable sort (GNU): sort -s -k1,1 file


Verification / Alternative check:
Compare the output of 'sort' with an editor's sorted view, or use 'uniq' afterwards to collapse duplicates if de-duplication is also desired. For numeric data, verify that '-n' is used; otherwise 10 may appear before 2 due to string comparison rules.


Why Other Options Are Wrong:

  • sort - r: Represents reverse sorting (and contains a spacing error); it is not the default ascending order.
  • sh: Invokes the shell, not a sorting utility.
  • st: Not a standard Unix command.
  • None of the above: Incorrect because 'sort' is correct.


Common Pitfalls:
Forgetting '-n' for numeric fields, ignoring locale effects on ordering, or sorting the wrong column when working with delimited data without specifying '-k' and '-t' properly.


Final Answer:
sort

Discussion & Comments

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