在bash中拆分存储在数组中的字符串

时间:2014-05-11 19:56:54

标签: arrays string bash

我是bash的新手,但是我无法尝试拆分存储在数组中的字符串,然后将这些拆分值存储到单独的变量中。例如,我有一个字符串,如

dan 2014-05-06

这是数组中的第一个元素,我想将该字符串拆分为2个单独的变量

  

名=担

     

日期= 2014年5月6日

有一种简单的方法吗?

2 个答案:

答案 0 :(得分: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]"

答案 1 :(得分: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]}一次并不是太糟糕。)