Computing.Net > Forums > Unix > sh Find the length of a string

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

sh Find the length of a string

Reply to Message Icon

Name: ozbodd
Date: May 21, 2006 at 13:28:29 Pacific
OS: Unix
CPU/Ram: na
Product: na
Comment:

How do I set a variable to the character length of a string? I have tried several such as

n=len($a)
n=length($a)
set n [string length $a]

They do not seem to work.



Sponsored Link
Ads by Google

Response Number 1
Name: nails
Date: May 21, 2006 at 18:12:41 Pacific
Reply:

You can find a string length any number of ways.

The korn shell has a length operator:
var="mystring"
len=${#var}
echo $len # shows 8

For older shells like the Bourne shell, you can also use external unix tools like awk or perl. Here's my favorite solution using expr:

len=`expr $var : '.*'`
echo $len


0

Response Number 2
Name: ghostdog
Date: May 21, 2006 at 21:42:58 Pacific
Reply:

or you could do
length=`echo -n "string" | wc -m`
echo "length of string is $length"


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: sh Find the length of a string

Length of file names in Unix www.computing.net/answers/unix/length-of-file-names-in-unix/2186.html

finding length of a field in shell www.computing.net/answers/unix/finding-length-of-a-field-in-shell/7053.html

Find length of each line in a file. www.computing.net/answers/unix/find-length-of-each-line-in-a-file/7852.html