20

I need to calculate the length of a string using pure sh shell only. What is happening is that /bin/sh is actually a soft link to bash or another shell. Hence ${#STRING} gives the length of string as it is advance bash feature.

Can someone tell me how I can find length of string? I am using Solaris 5.10 Sparc architecture

Tsundoku
  • 172

9 Answers9

21

wc -m counts the chars in a string. So you can do something like:

STRLENGTH=$(echo -n $STRING | wc -m)

Alternative syntax:

STRLENGTH=`echo -n $STRING | wc -m`

The -n flag for echo stops it from printing a newline. The flag might be different on Solaris 5. Check man echo

18

Here are couple of ways to do it.

myvar="This is a test"
echo "${#myvar}"
14

Or

expr length "${myvar}"
14
R J
  • 660
9

Using ${#string} to get the length of $string is a POSIX shell parameter expansion. It is not a bash-only feature.

On Solaris 5.10, if /bin/sh or /usr/bin/sh (as mentioned in the sh(1) manual) does not support this, then /usr/xpg4/bin/sh will.

To get POSIX behaviour on a Solaris 5.10 system, your PATH should be set to

/usr/xpg6/bin:/usr/xpg4/bin:/usr/ccs/bin:/usr/bin

(in that order), as described in the standards(5) manual.

Kusalananda
  • 2,369
  • 18
  • 26
4

Here is couple of ways :

echo ${#VAR}
echo -n $VAR | wc -m
echo -n $VAR | wc -c
printf $VAR | wc -m
expr length $VAR
expr $VAR : '.*'

http://techopsbook.blogspot.in/2017/09/how-to-find-length-of-string-variable.html

1

(Though there are already many answers, but feels they are not so intuitive, so I would add one to make it clear on first sight)

If you just want to do it in shell (bash) command line (or even script).

You can use either of following ways:

  • Use echo -n and wc -m
  • Use printf and wc -m

e.g

# 5
echo -n hello | wc -m

# 11
echo -n "hello world" | wc -m

# 5
printf "hello" | wc -m

# 11
printf "hello world" | wc -m

# 11
printf "hello %s" world | wc -m

Tips:

  • echo by default will append a new line at end, so -n option is needed to avoid that.
  • If there are space among input string, then should quote it.
Eric
  • 401
1

using awk: Works from any type of shell

set xxx = "12345"

echo $xxx | awk '{ print length }'

5

1

I don't think "pure sh" can do it. But you don't need to do anything in "pure sh"; you need to do it in sh plus standard utilities. The most straightforward way is:

strlength=`expr "$string" : ".*"`

(expr is POSIX). Or if you don't have expr (Solaris 5.1 is ancient), you could also use wc together with printf like:

strlength=`printf "%s" "$string" | wc -m`

Just don't try to use echo, because echo will add trailing newlines and there is no standard way to suppress it.

Note that wc -m counts characters and wc -c counts bytes if there is a difference in current locale.

Jan Hudec
  • 1,025
-1

set var="test test test";

echo $%var;

14

-2

You could do this fairly simply in python

>>> len('hello world')
11
Journeyman Geek
  • 133,878
g10guang
  • 99
  • 1