I will be posting a series of posts on scripting starting from some basic commands, control structures, small scripts and then moving to some complete practical scripts for general server automation, monitoring, reporting and backups which I would hope one can follow in sequence and learn scripting.
This would be first one in this series of posts starting with a basic string/character translation command tr.
tr is a very useful command that helps us to operate on characters and perform different functions on them. The tr command is part of the coreutils package/rpm.
root@centos[~]# which tr
root@centos [~]# rpm -qf /usr/bin/tr
It can be used to perform functions like changing the case of characters e.g. from upper to lower case or vice versa, delete, complement, replace or squeeze repeat characters etc. Lets look at some basic examples.
Below is an example of how we can use it to change the case of characters :
root@centos [~]# echo STRINGINCAPS1 | tr A-Z a-z
root@centos [~]# echo stringinsmallletters1 | tr a-z A-Z
The output and usage is pretty much obvious, so I will leave it to you to test it on your end. Lets look another example of squeezing repeating characters in a string :
root@centos [~]# echo REPEEEATchars | tr -s A-Z
As you can see the repeated ‘E’ in the string have been squeezed to single character after translation by using -s switch with the tr command.
These are just some basic examples to get you started, you can learn more options available, using commands tr –help and man tr. We can e.g. use the tr command in loop to change case of all files in a directory from caps to lower case or vice versa. Or required character replacements can be performed using -c switch.
In the next post I will discuss the cut command which is a very powerful string parsing command that is used very commonly in the bash scripts to parse and then select certain section/part from some output.