Process text streams using filters: Tr

«« Previous
Next »»

For this LPIC-1 objective, 103.2 we look at using the Linux command tr to translate and delete characters. This objective has look at many of the smaller tools that you can use within Linux but these all build to make a strong tool-set. No matter if the tools are used by themselves are part of a command pipeline

Examples with tr


The Linux command tr allows you to translate single characters,additionally we can delete characters and squeeze them. Squeezing is not quite as fun as it sounds but is very useful in removing additional spaces

We will start with the first example of tr and will use it to convert lowercase strings to uppercase:

echo "a b c" | tr [a-z]  [A-Z]
A B C

Now although this may well work for you and it will work, Linux likes to be able to provide alternatives; this could also be written as:

echo "a b c" | tr [:lower:]  [:upper:]

Don’t you just love choice, you can now choose your favorite and stick with it but you will need to understand both methods for the LPIC-1 exam and also for reading other people’s scripts

In the nest example we look at using tr to delete newline characters , the n, the command line  we could use would be similar to this:

echo -e "a nb" | tr -d "n"
a b

We can see from the output that the a an b are on the same line and we have removed the newline from the echo string.

For example three, when you are ready, we will squeeze or suppress contiguous spaces we could use code similar to the following

echo "a b     c" | tr -s [:space:]
a b c

Suppressing the extra spaces ensures just single spacing between words or fields; this may be useful when displaying the /etc/fstab file that always has additional spaces:

cat /etc/fstab |  tr -s [:space:]

Hopefully you too can find some great ways to use this and you start practicing with tr as soon as you can. Take a look at the video and before to establish a great foundation for your LPIC-1 certification.


«« Previous
Next »»

0 comments:

Post a Comment