Shell script to find the length of a string

awk has a built in function called length with which you can find the length of a string. The following shell script shows how to find the length of the string with awk

#!/bin/sh
#Shell script to find the length of the string

string="Joys of Programming"
length=`echo|awk "{print length("$string")}"`
echo "Length of the string "$string" is $length"

On executing the program

$ ./length.sh 
Length of the string "Joys of Programming" is 19

You can even find the length from the terminal with this simple command

$ awk 'BEGIN {print length("Joys of Programming")}'
19

or

$ echo|awk '{print length("Joys of Programming")}'
19

Thus you can see that the syntax of length function is

length(string)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s