DEV Community

Cover image for Bash Transform and Sort commands
Damon Marc Rocha II
Damon Marc Rocha II

Posted on

Bash Transform and Sort commands

The Transform and Sort commands are another useful set of tricks to add to your bash toolbelt. The Transform command is used to replace parts of a string, file, or text with a chosen delimiter. The next section covers how to use this command and gives a few examples.

Transform

The template for the transform command is as follows:

any type of text | tr "replace" "with" 
Enter fullscreen mode Exit fullscreen mode

Before the pipe, any type of string or text reading can be used. Then after the transform or 'tr', you can put what you want replaced in the first set of parentheses and what you want it replaced within the second. A few examples are displayed below:

echo "Hello" | tr "e" "E"
//=> HEllo

echo "Hello how are you" | tr " " '-'
//=> Hello-how-are-you

echo "Hello how are you 1234" | tr -d [0-9]
//=> Hello how are you 

echo "Hello how Are You" | tr -d [:lower:]
//=> H A Y
Enter fullscreen mode Exit fullscreen mode

The third and fourth example implements an alternate template to use with the transform command. Instead of directly replacing a certain character you can instead give a flag, like the delete flag above, and then provide what you want that flag applied to. So the third command above says to delete all numbers in the text and the fourth tells the transform to delete all lowercase letters. The tr command can be used to format text in hundreds of ways, if you want to read some more on tr look here. Now on to the sort command.

Sort

So as its name implies, the sort command will sort input in text or TSV formats in various different ways. A number of flags are often used in addition to sort which changes the sorting method to the following:

  • No Flag: The vanilla sort command simply sorts the lines of the input file in lexicographical order.
  • -n Flag: sorts the file on the basis of the numeric fields available if the first word or column in the file is a number.
  • -r Flag: option reverses the sorting order to either the reverse of the usual lexicographical ordering or descending order while sorting in numerical mode.
  • -k Flag: useful while sorting a table of data (tsv, csv etc.) based on a specified column (or columns).
  • -t Flag: used while specifying a delimiter in a particular file where columns are separated by tabs, spaces, pipes etc.

Due to the examples of sort being lengthy, I decided to leave them out and either allow you to try it out yourself or look at the resources. Here are a few links with some great examples of using sort
Sort Wiki Page
Sort examples
Youtube video

Top comments (0)