Objective: Count the number of characters in a shell variable.
If you are using bash
shell, parameter expansion can be used to get the length. If not, the wc
or awk
utilities can be used. So, let’s say that we want to count the number of characters in the variable $var
.
1 |
$ var="Hello World" |
To count the number of characters using wc
, use the following syntax.
1 2 |
$ echo -n $var | wc -c 11 |
Make sure that the “-n
” option is specified to the echo
command, else wc
will count the newline character as well. Note that spaces are counted as characters as well.
To count the number of characters using awk
, use the following syntax.
1 2 |
$ echo $var | awk '{print length($0)}' 11 |
This time round, the “-n
” option need not be specified for the echo
command.
On POSIX shells (bash, ksh, etc) use parameter expansion to get the string length.
1 2 |
$ echo "${#var}" 11 |