The sort command can sort output alphabetically or numerically. Not every program sorts its output, but you can pipe the output to sort when needed.
Remember the words.txt file you created earlier?
| $ cat words.txt |
| blue |
| apple |
| candy |
| hand |
| fork |
Use sort to sort the lines of the file alphabetically:
| $ sort words.txt |
| apple |
| blue |
| candy |
| fork |
| hand |
Using the -r switch, you can sort the file in reverse:
| $ sort -r words.txt |
| hand |
| fork |
| candy |
| blue |
| apple |
Using the -R flag will sort the lines randomly.
sort on macOS | |
---|---|
The -R option is only available on the GNU version of sort. If you’re on a Mac, you won’t have this option, as it comes with the BSD version. You can use Homebrew to install the GNU version of sort and other tools by using brew install coreutils. See Installing coreutils, for how to do that. |
| $ sort -R words.txt |
| apple |
| blue |
| candy |
| fork |
| hand |
Like other programs, you can use sort in a pipeline, which means you can use it to sort output of another command.
Next, let’s look at sed, a tool that lets you edit streams of text on the fly.
18.191.78.136