DEV Community

Cover image for sort command
Mohamed Yahia
Mohamed Yahia

Posted on • Edited on

sort command

The default function of sort command and the -r or --reverse option

nuclearegg69@zenbook-f13:~$ cat unsorted.txt
white apple
yellow orange
black banana
hannah montana
cheetah in the savanna
nuclearegg69@zenbook-f13:~$ sort unsorted.txt
black banana
cheetah in the savanna
hannah montana
white apple
yellow orange
nuclearegg69@zenbook-f13:~$ sort -r unsorted.txt
yellow orange
white apple
hannah montana
cheetah in the savanna
black banana
Enter fullscreen mode Exit fullscreen mode

-u option or --unique prints only unique lines while sorting

nuclearegg69@zenbook-f13:~$ nano unsorted.txt
nuclearegg69@zenbook-f13:~$ cat unsorted.txt
white apple
white apple
yellow orange
yellow orange
black banana
hannah montana
cheetah in the savanna
nuclearegg69@zenbook-f13:~$ sort -u unsorted.txt
black banana
cheetah in the savanna
hannah montana
white apple
yellow orange
Enter fullscreen mode Exit fullscreen mode

Sorting numbers

nuclearegg69@zenbook-f13:~$ cat unsortedNums.txt
1
2
188
9
78
nuclearegg69@zenbook-f13:~$ sort unsortedNums.txt
1
188
2
78
9
nuclearegg69@zenbook-f13:~$ sort -n unsortedNums.txt
1
2
9
78
188
Enter fullscreen mode Exit fullscreen mode

The sort command by default doesnt work for numbers because it compares character by character so first number in 188 is 'more up in the list of numbers' than 2 so 188 goes first, so we have to use -n or --numeric-sort for it work as we would expect.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay