How to sort unique lines?

To sort unique lines in a file, you can use a combination of the sort and uniq commands. Here’s how to do it:

Step-by-Step Instructions

  1. Sort the File: First, you need to sort the lines in the file. This is necessary because the uniq command only removes adjacent duplicate lines.

  2. Use uniq: After sorting, you can use the uniq command to filter out the duplicate lines.

Example Command

Assuming you have a file named data.txt with the following content:

apple
banana
apple
cherry
banana
date

You can sort the unique lines using the following command:

sort data.txt | uniq

Explanation

  • sort data.txt: This sorts the lines in data.txt.
  • |: This is a pipe that takes the output of the sort command and uses it as input for the uniq command.
  • uniq: This filters out duplicate lines from the sorted output.

Output

The output will be:

apple
banana
cherry
date

Additional Options

If you want to sort the unique lines and also ignore case, you can use:

sort -f data.txt | uniq

If you want to sort and keep only unique lines while also counting occurrences, you can use:

sort data.txt | uniq -c

This will output the count of each unique line along with the line itself.

0 Comments

no data
Be the first to share your comment!