[bash] bash의 문자열 길이

변수에 저장된 문자열의 길이를 어떻게 다른 변수에 할당합니까?

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

다른 변수를 출력으로 11어떻게 설정 합니까?



답변

UTF-8 문자열 길이

fedorqui의 정답 외에도 문자열 길이와 바이트 길이의 차이를 보여주고 싶습니다.

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

렌더링합니다 :

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

저장된 문자를 볼 수도 있습니다.

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"

대답합니다 :

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

참고 : Isabell Cowan의 의견 에 따르면에 설정을 추가 $LC_ALL했습니다 $LANG.

인수의 길이

인수는 일반 변수와 동일하게 작동

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"
}

로 작동합니다

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

유용한 printf수정 도구 :

만약 너라면:

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

정말 예쁘지 않습니다 … 이것에는 약간의 기능이 있습니다.

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

그런 다음 :

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 uses %2d bytes\n" \
        "'$string'" ${#string} $((${#string}+$?))
  done

 - 'Généralités'  is 11 chars length, but uses 14 bytes
 - 'Language'     is  8 chars length, but uses  8 bytes
 - 'Théorème'     is  8 chars length, but uses 10 bytes
 - 'Février'      is  7 chars length, but uses  8 bytes
 - 'Left: ←'      is  7 chars length, but uses  9 bytes
 - 'Yin Yang ☯'   is 10 chars length, but uses 12 bytes

불행히도 이것은 완벽하지 않습니다!

그러나 이중 간격 문자, 0 간격 문자, 역 변위 및 기타 단순하지 않은 이상한 UTF-8 동작이 남아 있습니다 …

더 많은 제한 사항 은 diffU8test.sh 또는 diffU8test.sh.txt 를 참조하십시오.


답변

변수에 저장된 문자열의 길이를 얻으려면 다음과 같이하십시오.

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

제대로 저장되었는지 확인하려면 다음을 수행 echo하십시오.

$ echo "$size"
11


답변

당신이 사용할 수있는:

MYSTRING="abc123"
MYLENGTH=$(printf "%s" "$MYSTRING" | wc -c)
  • wc -c또는 wc --bytes바이트 수 = 유니 코드 문자는 2, 3 개 이상의 바이트로 계산됩니다.
  • wc -m또는 wc --chars문자 수 = 유니 코드 문자는 더 많은 바이트를 사용할 때까지 단일 문자로 계산됩니다.

답변

가장 간단한 경우를 원했고 결과는 다음과 같습니다.

echo -n 'Tell me the length of this sentence.' | wc -m;
36


답변

이것을 명령 행 또는 함수 인수와 함께 사용하려면 size=${#1}대신 대신 사용하십시오 size=${#$1}. 두 번째는 더 본능적이지만 잘못된 구문입니다.


답변

게시물 시작에 대한 응답으로 :

이것을 명령 행 또는 함수 인수와 함께 사용하려면 …

코드와 함께 :

size=${#1}

길이가 0 인 인수를 확인하고 변수를 저장할 필요가없는 경우가있을 수 있습니다. 이런 종류의 구문을 사용할 수 있다고 생각합니다.

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

Bash 조건식의 전체 목록은 GNUwooledge 를 참조하십시오 .


답변

제공된 예제를 사용하여

#KISS (Keep it simple stupid)
size=${#myvar}
echo $size