kemal ozdogan
kemal ozdogan

Reputation: 81

How to can I count the lenght of an parameter without any spaces or numbers?

I am trying to count the seize of an parameter without the numbers and spaces, like if someone types in "Hello player1" it has to echo "11 characters". I have tried using ${#value} but this counts numbers and spaces.

    if [ -z "$1" ]
    then
        echo "write at least 1 word"
else
    for value in "$@" 
        do
            echo "${value//[[:digit:]]/}"
            
    done
    echo ${#value}
fi

The result of the code

as you can see in the image it counts only the last parameter and counts the numbers what I don't want

Results of the second code

Upvotes: 0

Views: 47

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295315

Break it into two steps.

set -- "abc 123" "d12"
for value do  # in "$@" is default, don't need to say it
  valueTrimmed=${value//[[:digit:][:space:]]/}
  echo "The string '$value' has ${#valueTrimmed} valid characters"
done

...properly emits as output:

The string 'abc 123' has 3 valid characters
The string 'd12' has 1 valid characters

bash does not support nesting parameter expansions; you cannot do this in one step as a shell builtin (it could be done in a pipeline, but only with an unreasonably high performance cost).

Upvotes: 4

Related Questions