이 기사에서는 bash 스크립트에서 문자열을 분할하는 방법에 대해 설명합니다.
단일 문자열을 여러 문자열로 나누는 것을 문자열 분할이라고 합니다. 많은 프로그래밍 언어에는 문자열 분할을 수행하는 내장 함수가 있지만 bash에는 이를 수행하는 내장 함수가 없습니다. Bash에서 문자열 분할을 수행하는 다양한 방법이 있습니다. 예제를 통해 모든 방법을 하나씩 살펴보겠습니다.
방법 1: IFS 변수 사용
$IFS(Internal Field Separator)는 특수 쉘 변수입니다. 구분 기호(문자열을 분할하려는 기준이 되는 하나 이상의 문자 시퀀스)를 할당하는 데 사용됩니다. ' ', ' ', '-' 등과 같은 값이나 문자는 구분 기호가 될 수 있습니다. $IFS 변수에 값을 할당한 후 문자열 값을 읽어야 합니다. '-r' 및 '-a' 옵션을 사용하여 문자열을 읽을 수 있습니다.
- '-r': 백슬래시()를 이스케이프 문자 대신 문자로 읽습니다.
- '-a': -a 옵션 뒤에 선언된 배열 변수에 분할된 단어를 저장하는 데 사용됩니다.
예시 1: 문자열을 공백으로 분할
반응형 지도
암호:
#!/bin/bash # String text='Welcome to techcodeview.com' # Set space as the delimiter IFS=' ' # Read the split words into an array # based on space delimiter read -ra newarr <<< '$text' # Print each value of the array by using # the loop for val in '${newarr[@]}'; do echo '$val' done> 산출:
Welcome to techcodeview.com>
예 2: 문자열을 기호로 분할
@ 기호를 사용하여 문자열을 분할합니다.
자바에서 파일을 여는 방법
암호:
#!/bin/bash #String text='Welcome@[email protected]@!!' # Set @ as the delimiter IFS='@' # Read the split words into an array # based on space delimiter read -ra newarr <<< '$text' # Print each value of the array by # using the loop for val in '${newarr[@]}'; do echo '$val' done>
산출:
Welcome to techcodeview.com !!>
방법 2: IFS 변수를 사용하지 않음
이 방법에서는 -d 옵션이 포함된 readarray 명령을 사용하여 문자열 데이터를 분할합니다. '-d': 이 옵션은 구분 기호를 정의하는 IFS 변수 역할을 합니다.
예시 1: 문자열을 공백으로 분할
암호:
#!/bin/bash # Read the main string text='Welcome to techcodeview.com' # Split the string by space readarray -d ' ' -t strarr <<< '$text' # Print each value of the array by # using loop for (( n=0; n < ${#strarr[*]}; n++)) do echo '${strarr[n]}' done> 이제 스크립트가 어떻게 작동하는지 살펴보겠습니다.
자바 비교 문자열
- 스크립트는 다음의 값을 설정합니다.
text>techcodeview.com에 오신 것을 환영합니다. - 그만큼
readarray>명령은 공백을 구분 기호로 사용하여 문자열을 배열로 분할하여 배열을 만듭니다.strarr>다음 요소가 포함되어 있습니다: techcodeview.com에 오신 것을 환영합니다. - for 루프는 각 요소를 반복합니다.
strarr>정렬. - 각 요소를 별도의 줄에 하나씩 인쇄합니다.
산출:
Welcome to techcodeview.com>
예 2: 다음을 사용하여 분할 ㅏ 콜론 ㅏ 구분 기호
암호:
#!/bin/bash # Read the main string text='Welcome:to:techcodeview.com' # Split the string based on the delimiter, ':' readarray -d : -t strarr <<< '$text' # Print each value of the array by using # loop for (( n=0; n < ${#strarr[*]}; n++)) do echo '${strarr[n]}' done> 산출:
자바 하위 문자열
Welcome to techcodeview.com>
방법 3: 다중 문자 구분 기호를 사용하여 문자열 분할
이 방법에서는 변수가 문자열 데이터를 저장하는 데 사용되고 다른 변수는 다중 문자 구분 기호 데이터를 저장하는 데 사용됩니다. 분할된 문자열을 저장하기 위해 배열 변수도 선언됩니다.
암호:
# Define the string to split text='HelloRomy HelloPushkar HelloNikhil HelloRinkle' # store multi-character delimiter delimiter='Hello' # Concatenate the delimiter with the # main string string=$text$delimiter # Split the text based on the delimiter newarray=() while [[ $string ]]; do newarray+=( '${string%%'$delimiter'*}' ) string=${string#*'$delimiter'} done # Print the words after the split for value in ${newarray[@]} do echo '$value ' done> 산출:
Romy Pushkar Nikhil Rinkle>