Programing

Bash에서 문자열을 대문자에서 소문자로 변환하는 방법은 무엇입니까?

lottogame 2020. 10. 18. 08:17
반응형

Bash에서 문자열을 대문자에서 소문자로 변환하는 방법은 무엇입니까?


이 질문에 이미 답변이 있습니다.

문자열 값을 대문자에서 소문자로 변환하는 방법을 찾고 있습니다. 모든 검색 결과는 tr명령 사용 방법을 보여줍니다 .

tr명령 의 문제점 은 echo 문과 함께 명령을 사용할 때만 결과를 얻을 수 있다는 것입니다. 예를 들면 :

y="HELLO"
echo $y| tr '[:upper:]' '[:lower:]'

위의 결과는 'hello'가되지만 결과를 아래와 같이 변수에 할당해야합니다.

y="HELLO"
val=$y| tr '[:upper:]' '[:lower:]'
string=$val world

위와 같이 값을 할당하면 빈 결과가 나타납니다.

추신 : 내 Bash 버전은 3.1.17입니다.


bash 4를 사용하는 경우 다음 접근 방식을 사용할 수 있습니다.

x="HELLO"
echo $x  # HELLO

y=${x,,}
echo $y  # hello

z=${y^^}
echo $z  # HELLO

,또는 하나만 사용 ^하여 첫 글자 lowercase또는 uppercase.


코드를 구현하는 올바른 방법은

y="HELLO"
val=$(echo "$y" | tr '[:upper:]' '[:lower:]')
string="$val world"

이것은 $(...)표기법을 사용 하여 변수의 명령 출력을 캡처합니다. 또한 참고 주위에 따옴표 string변수 - 당신이 그들을 필요는 것을 나타냅니다 $valworld할당 할 수있는 하나의 일이다 string.

bash4.0 이상인 경우 더 효율적이고 우아한 방법은 bash내장 문자열 조작 을 사용하는 것입니다 .

y="HELLO"
string="${y,,} world"

참고 tr만 어떤하고, 일반 ASCII를 처리 할 수있는 tr국제 문자에 직면 할 때 기반 솔루션은 실패합니다.

bash 4 기반 ${x,,}솔루션도 마찬가지입니다 .

반면 awk에이 도구는 UTF-8 / 멀티 바이트 입력도 올바르게 지원합니다.

y="HELLO"
val=$(echo "$y" | awk '{print tolower($0)}')
string="$val world"

liborw의 답변 .


왜 백틱으로 실행하지 않습니까?

 x=`echo "$y" | tr '[:upper:]' '[:lower:]'` 

This assigns the result of the command in backticks to the variable x. (i.e. it's not particular to tr but is a common pattern/solution for shell scripting)

You can use $(..) instead of the backticks. See here for more info.


I'm on Ubuntu 14.04, with Bash version 4.3.11. However, I still don't have the fun built in string manipulation ${y,,}

This is what I used in my script to force capitalization:

CAPITALIZED=`echo "${y}" | tr '[a-z]' '[A-Z]'`

If you define your variable using declare (old: typeset) then you can state the case of the value throughout the variable's use.

$ declare -u FOO=AbCxxx
$ echo $FOO
ABCXXX

"-l" does lc.


This worked for me. Thank you Rody!

y="HELLO"
val=$(echo $y | tr '[:upper:]' '[:lower:]')
string="$val world"

one small modification, if you are using underscore next to the variable You need to encapsulate the variable name in {}.

string="${val}_world"

참고URL : https://stackoverflow.com/questions/11392189/how-to-convert-a-string-from-uppercase-to-lowercase-in-bash

반응형