Sorting Output
Learn how to sort the output in the CLI.
We'll cover the following
The sort
command
The sort
command can sort output alphabetically or numerically. Not every program sorts its output, but we can pipe the output to sort when needed.
Remember the words.txt
file we created earlier? Let’s use sort
to sort the lines of the file alphabetically:
$ sort words.txt
Run the complete code on the terminal below for practice.
cat << 'EOF' > words.txt
blue
apple
candy
hand
fork
EOF
sort words.txt
We can use the -r
switch to sort the file in reverse with the following code: sort -r words.txt
.
We can use the -R
flag to sort the lines randomly with the following code: sort -R words.txt
.
Like with other programs, we can use sort
in a pipeline, which means we can use it to sort the output of another command.
The same switches apply to numeric inputs.
Use the terminal below for practice.
Get hands-on with 1400+ tech skills courses.