2014-05-11 4 views
1

저는 bash를 처음 사용 합니다만, 배열에 저장된 문자열을 분할하고 분리 된 값을 개별 변수에 저장하는 데 문제가 있습니다. 예를 들어, I는 문자열이 같은bash에서 배열 안에 저장된 문자열을 분할합니다.

어레이의 첫 번째 요소이며, I는 2 개 개의 별도의 변수

NAME = 댄

날짜에 해당 문자열을 분할 할

dan 2014-05-06 

= 2014-05-06

간단한 방법이 있나요?

답변

2

하나의 옵션은 read을 사용하는 것입니다

#!/usr/bin/env bash 

# sample array 
someArray=('dan 2014-05-06' 'other' 'elements') 

# read the 1st element into 2 separate variables, relying 
# on the default input-field separators ($IFS), which include 
# spaces. 
# Using -r is good practice in general, as it prevents `\<char>` sequences 
# in the input from being interpreted as escape sequences. 
# Note: `rest` would receive any additional tokens from the input, if any 
#  (none in this case). 
read -r name date rest <<<"${someArray[0]}" 

echo "name=[$name] date=[$date]" 
0
$ a=("dan 2014-05-06") 
$ b=(${a[0]}) 
$ printf "%s\n" "${b[@]}" 
dan 
2014-05-06 
$ name=${b[0]} 
$ date=${b[1]} 
$ echo "Name = $name" 
dan 
$ echo "Date = $date" 
2014-05-06 
$ 

배열 할당 b에 분할 공백에 ${a[0]}. 할당이 namedate 일 필요가있을 수도 있고 없을 수도 있습니다. 그것은 당신이 그들을 얼마나 사용할 것인지에 달려 있습니다. (스크립트가 길거나 변수가 많이 사용되는 경우 명명 된 변수를 사용하면 더 명확 해집니다. ${b[0]}${b[1]}을 각각 사용하면 나쁘지 않습니다.)

관련 문제