Tuesday, April 27, 2010

How to find the length of a variable?



    In UNIX, one deals with variables all the times. Many a time, you might want to find the length of a variable. The length of a variable can be found or calculated using many different ways in UNIX. Lets explore the different ways to do it:

1. In the k-shell or bourne shell, the simple echo command can be used to find the length of a variable.
#VAR="welcome"
#echo ${#VAR}
7
#

2. The echo command with wc can also be used to find the length of a variable.
#VAR="welcome"
#echo -n $VAR | wc -c
7
#

3. The printf command with wc can also be used to calculate the length of a variable.
#VAR="welcome"
#printf $VAR | wc -c
7
#

4. The expr command can also be used to find the length of a variable.
#VAR="welcome'
#expr $VAR : '.*'
7
#

5. The awk command can also be used to calculate the length of the variable.

#VAR="welcome"
#echo $VAR | awk '{print length ;}'
7
#

6. The perl command can also be used for the same:

#VAR="welcome"
#echo $VAR | perl -ne 'chop; print length($_) . "\n";'
7
#

    All the above examples all common across all UNIX flavors such as Solaris, HP-UX, Linux, AIX, etc.

[Note: In the above examples, the setting of variable VAR is shown with respect to k-shell/bourne shell. Depending on your shell, the setting of VAR variable will change.]
Related Posts Plugin for WordPress, Blogger...

No comments:

Post a Comment