Shell Programming Blog Shell Programming Blog

Sunday 23 September 2012

How to find the length of a string in Linux/Unix Shell scripting

Unknown | 20:16 |



While writing a shell script you might want to find the length of a string. While reading GNU expr command man page I found an interesting option:

expr length STRING

For example display the length of "abusittik" word:
expr length "abusittik"

Output:
9

expr and POSIX

However expr command is not concerned with POSIX (open system standards based on Unix). You can try old good KSH/Bash command (also following command should work with other UNIX like OSes such as FreeBSD / Solaris ):

myVar="abusittik"
echo ${#myVar}


Output:
9

Using AWK :

% echo abusittik | awk ‘ { print length } ‘

Output : 9

Using Perl:
 % echo abusittik | perl -nle ‘ print length ‘

Output : 9

2 comments:

  1. Great blog, thanks for taking time to share this page. It is really helpful. I have learned how to find the length of a string in Linux/Unix Shell scripting. Keep up the good work and share more.
    Unix Training institutes in Chennai | Unix certification in Chennai

    ReplyDelete
  2. Great content. Well written and well executed. I'm glad that I came across your post. Keep posting. Regards.
    Unix Training in Chennai | Unix Shell Scripting Training in Chennai | Unix Course in Chennai

    ReplyDelete

Don't just read and walk away, Your Feedback Is Always Appreciated. I will try to reply to your queries as soon as time allows.

Note:
1. If your question is unrelated to this article, please use our Facebook Page.
2. Please always make use of your name in the comment box instead of anonymous so that i can respond to you through your name and don't make use of Names such as "Admin" or "ADMIN" if you want your Comment to be published.
3. Please do not spam, spam comments will be deleted immediately upon my review.

Regards,
Mohamed Abubakar Sittik A

 

Shell Programming Copyright © 2012 Shell Programming theme is Designed by Abusittik, Shell Programming