Longitud de la cuerda en bash


¿Cómo se obtiene la longitud de una cadena almacenada en una variable y se asigna a otra variable?

myvar="some string"
echo ${#myvar}  
# 11

¿Cómo se establece otra variable en la salida 11?

Author: Brad Larson, 2013-06-28

9 answers

UTF-8 longitud de cadena

Además de la respuesta correcta de fedorqui , me gustaría mostrar la diferencia entre la longitud de la cadena y la longitud del byte:

myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
LANG=$oLang LC_ALL=$oLcAll
printf "%s is %d char len, but %d bytes len.\n" "${myvar}" $chrlen $bytlen

Rendirá:

Généralités is 11 char len, but 14 bytes len.

Incluso podrías echar un vistazo a los caracteres almacenados:

myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
printf -v myreal "%q" "$myvar"
LANG=$oLang LC_ALL=$oLcAll
printf "%s has %d chars, %d bytes: (%s).\n" "${myvar}" $chrlen $bytlen "$myreal"

Responderá:

Généralités has 11 chars, 14 bytes: ($'G\303\251n\303\251ralit\303\251s').

Nota: De acuerdo con El comentario de Isabell Cowan, he agregado configuración a $LC_ALL junto con $LANG.

Longitud de un argumento

Trabajo de argumento igual que las variables regulares

strLen() {
    local bytlen sreal oLang=$LANG oLcAll=$LC_ALL
    LANG=C LC_ALL=C
    bytlen=${#1}
    printf -v sreal %q "$1"
    LANG=$oLang LC_ALL=$oLcAll
    printf "String '%s' is %d bytes, but %d chars len: %s.\n" "$1" $bytlen ${#1} "$sreal"
}

Funcionará como

strLen théorème
String 'théorème' is 10 bytes, but 8 chars len: $'th\303\251or\303\250me'

Útil printf herramienta de corrección:

Si usted:

for string in Généralités Language Théorème Février  "Left: ←" "Yin Yang ☯";do
    printf " - %-14s is %2d char length\n" "'$string'"  ${#string}
done

 - 'Généralités' is 11 char length
 - 'Language'     is  8 char length
 - 'Théorème'   is  8 char length
 - 'Février'     is  7 char length
 - 'Left: ←'    is  7 char length
 - 'Yin Yang ☯' is 10 char length

No realmente bastante ... Para esto, hay una pequeña función:

strU8DiffLen () { 
    local bytlen oLang=$LANG oLcAll=$LC_ALL
    LANG=C LC_ALL=C
    bytlen=${#1}
    LANG=$oLang LC_ALL=$oLcAll
    return $(( bytlen - ${#1} ))
}

Entonces ahora:

for string in Généralités Language Théorème Février  "Left: ←" "Yin Yang ☯";do
    strU8DiffLen "$string"
    printf " - %-$((14+$?))s is %2d chars length, but use %2d bytes\n" \
        "'$string'" ${#string} $((${#string}+$?))
  done 

 - 'Généralités'  is 11 chars length, but use 14 bytes
 - 'Language'     is  8 chars length, but use  8 bytes
 - 'Théorème'     is  8 chars length, but use 10 bytes
 - 'Février'      is  7 chars length, but use  8 bytes
 - 'Left: ←'      is  7 chars length, but use  9 bytes
 - 'Yin Yang ☯'   is 10 chars length, but use 12 bytes
 164
Author: F. Hauri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-11 15:52:53

Para obtener la longitud de una cadena almacenada en una variable, diga:

myvar="some string"
size=${#myvar} 

Para confirmar que se guardó correctamente, echo esto:

$ echo "$size"
11
 376
Author: fedorqui,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-30 07:52:38

Puedes usar:

MYSTRING="abc123"
MYLENGTH=$(printf "%s" "$MYSTRING" | wc -c)
  • wc -c o wc --bytes para el recuento de bytes = Los caracteres Unicode se cuentan con 2, 3 o más bytes.
  • wc -m o wc --chars para el conteo de caracteres = Los caracteres Unicode se cuentan solos hasta que usan más bytes.
 15
Author: atesin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-26 21:23:32

Si desea usar esto con argumentos de línea de comandos o función, asegúrese de usar size=${#1} en lugar de size=${#$1}. El segundo puede ser más instintivo, pero es una sintaxis incorrecta.

 13
Author: Dick Guertin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-19 00:13:39

Aquí hay un par de formas de calcular la longitud de la variable:

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

Y para establecer el resultado en otra variable, simplemente asigne el comando anterior con comillas hacia atrás a otra variable de la siguiente manera:

otherVar=`echo -n $VAR | wc -m`   
echo $otherVar

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

 6
Author: Mukesh Shakya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-05 18:20:46

En respuesta al post a partir de:

Si desea usar esto con argumentos de línea de comandos o función...

Con el código:

size=${#1}

Podría darse el caso de que solo desee verificar un argumento de longitud cero y no tenga necesidad de almacenar una variable. Creo que puedes usar este tipo de sintaxis:

if [ -z "$1" ]; then
    #zero length argument 
else
    #non-zero length
fi

Ver GNUy wooledge para una lista más completa de expresiones condicionales Bash.

 5
Author: JGFMK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-26 23:07:33

Estaba tratando de hacer algo similar, pero solo quería asegurarme de que la entrada del usuario no fuera demasiado larga.

if [ ${#string} -ge 12 ]; then 
    echo ">= 12 characters. too long"
    exit
else 
    echo "under 12 characters, not too long."
fi
 4
Author: TrophyGeek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-26 22:42:19

Quería el caso más simple, finalmente este es un resultado:

echo -n 'Tell me the length of this sentence.' | wc -m;
36
 3
Author: dmatej,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-11 19:14:31

Usaría algo como esto:

var2=$(echo $myvar | wc -c)

No necesitas un script.

 -2
Author: Galaxy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-18 06:06:44