1

I am new to bash, but I am having trouble trying to split a string stored in array and then store those split values into separate variables. For example, I have a string such as

dan 2014-05-06

which is the first element in the array, and I want to split that string into 2 separate variables

name=dan

date=2014-05-06

Is there a simple way to do this?

BoJack Horseman
  • 4,406
  • 13
  • 38
  • 70
esseldm
  • 55
  • 4

2 Answers2

2

One option is to use 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]"
mklement0
  • 382,024
  • 64
  • 607
  • 775
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
$

The array assignment to b splits ${a[0]} at the white space. You might or might not need the assignments to name and date; it depends on how much you're going to use them. (Using the named variables is clearer if the script is long or the variables are used a lot; using ${b[0]} and ${b[1]} once each is not too bad.)

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278