Thursday, May 1, 2008

Understanding the tr command

tr copies the given input to produced the output with substitution or deletion of selected characters. It is frequently used in shell scripts.

tr [options] "set1" "set2"
echo something | tr "set1" "set2"
tr "set1" "set2" < input.txt
tr "set1" "set2" <> output.txt

For example, translate 'linux' to upper-case:
$ echo 'linux' | tr "[:lower:]" "[:upper:]"
$ echo 'linux' | tr "a-z" "A-Z"
$ echo 'I LovE linuX. one is better Than 2' | tr "a-z" "A-Z"

Create a list of the words in /path/to/file, one per line:
$ tr -cs "[:alpha:]" "\n" < /path/to/file
* -c : Complement the set of characters in string1
* -s : Replace each input sequence of a repeated character that is listed in SET1 with a single occurrence of that character

In the following example user will get confirmation before deleting the file. If the user responds in lower case, tr will do nothing, but in upper case, the character will be changed to lower case. This will ensure that even if user responds with YES, YeS, YEs etc; script should remove file:
echo -n "Enter file name : "
read myfile
echo -n "Are you sure ( yes or no ) ? "
read confirmation
confirmation="$(echo ${confirmation} | tr 'A-Z' 'a-z')"
if [ "$confirmation" == "yes" ]; then
[ -f $myfile ] && /bin/rm $myfile || echo "Error - file $myfile not found"
: # do nothing

Remove all non-printable characters from myfile.txt
$ tr -cd "[:print:]" < myfile.txt

Remove all two more successive blank spaces from a copy of the text in a file called input.txt and save output to a new file called output.txt:
tr -s ' ' ' ' <> output.txt

The -d option is used to delete every instance of the string (i.e., sequence of characters) specified in set1. For example, the following would remove every instance of the word nameserver from a copy of the text in a file called /etc/resolv.conf and write the output to a file called ns.ipaddress.txt:
tr -d 'nameserver' < /etc/resolv.conf > ns.ipaddress.txt

No comments: