Thursday, December 10, 2009

Some 'tr' useful examples

This is just a brief totorial for a great Unix tool called 'tr', very useful in text editing let's review couple of examples to make you understand the basics:
Before you start reading on I strongly recommend reading about regular expressions, a cool table that summarizes of reg. ex. can be found here:http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/
OK, so let's start - we will take a look at one of my directories:
paul# ls
file01.txt file02.txt file03.txt file04.txt file05.txt
Let's make an output of upper cases names:

paul# ls | tr '[:lower:]' '[:upper:]'
FILE01.TXT
FILE02.TXT
FILE03.TXT
FILE04.TXT
FILE05.TXT


Another example, let's try to extract out only the numbers of the following string:

paul# echo -e"Abc1234d56E\n" | tr -cd '[:digit:]'
123456


We want to replace blank spaces with the " - " character:

paul# ls
bla bla.txt file01.txt file02.txt file03.txt file04.txt

paul# ls | tr '[:blank:]' '_'
bla_bla.txt
file01.txt
file02.txt
file03.txt
file04.txt
file05.txt


There are numerous of good example for usage of 'tr' , I will try to add more in the future.

No comments: