Size: 484
Comment:
|
Size: 1083
Comment: portable (but ugly) expr method suggested in FreeBSD expr page to avoid case where "$varname"=length and using GNU expr :-/
|
Deletions are marked like this. | Additions are marked like this. |
Line 1: | Line 1: |
[[Anchor(faq7)]] | <<Anchor(faq7)>> |
Line 3: | Line 3: |
The fastest way, not requiring external programs (but usable only with ["BASH"] and KornShell): | The fastest way, not requiring external programs (but not usable in Bourne shells): |
Line 5: | Line 6: |
# POSIX | |
Line 8: | Line 10: |
or | or for Bourne shells: |
Line 11: | Line 13: |
# Bourne | |
Line 14: | Line 17: |
({{{expr}}} prints the number of characters matching the pattern {{{.*}}}, which is the length of the string) | ({{{expr}}} prints the number of characters matching the pattern {{{.*}}}, which is the length of the string.) |
Line 16: | Line 19: |
or | or: |
Line 19: | Line 22: |
# Bourne, with GNU expr(1) | |
Line 22: | Line 26: |
(for a BSD/GNU version of {{{expr}}}. Do not use this, because it is not ["POSIX"]). | (BSD/GNU {{{expr}}} only) This second version is not specified in [[POSIX]], so is not portable across all platforms. However, if {{{$varname}}} expands to {{{"length"}}}, the first version will fail with BSD/GNU {{{expr}}}. A portable way is: {{{ expr \( "X$varname" : ".*" \) - 1 }}} One may also use `awk`: {{{ # Bourne awk -v x="$varname" 'BEGIN {print length(x)}' }}} ------ Similar needs: {{{ # Korn/Bash ${#arrayname[@]} }}} Returns the number of elements in an array. {{{ # Korn/Bash ${#arrayname[i]} }}} Returns the length of the array's element i. ---- CategoryShell |
Is there a function to return the length of a string?
The fastest way, not requiring external programs (but not usable in Bourne shells):
# POSIX ${#varname}
or for Bourne shells:
# Bourne expr "$varname" : '.*'
(expr prints the number of characters matching the pattern .*, which is the length of the string.)
or:
# Bourne, with GNU expr(1) expr length "$varname"
(BSD/GNU expr only)
This second version is not specified in POSIX, so is not portable across all platforms. However, if $varname expands to "length", the first version will fail with BSD/GNU expr.
A portable way is:
expr \( "X$varname" : ".*" \) - 1
One may also use awk:
# Bourne awk -v x="$varname" 'BEGIN {print length(x)}'
Similar needs:
# Korn/Bash ${#arrayname[@]}
Returns the number of elements in an array.
# Korn/Bash ${#arrayname[i]}
Returns the length of the array's element i.