Aaron
Aaron

Reputation: 6704

Bash conditionally split string into array

I've browsed questions for splitting input based on a character but can't quite figure out multiple characters based on a condition:

Say I had a simply bash script that split input separated by spaces into an array:

echo "Terms:"
read terms            // foo bar hello world
array=(${terms// / }) // ["foo", "bar", "hello", "world"]

I want an extra condition where if terms are encapsulated by another character, the whole phrase should be split as one.

e.g. encapsulated with a back tick:

echo "Terms:"
read terms            // foo bar `hello world`
{conditional here}    // ["foo", "bar", "hello world"]

Upvotes: 0

Views: 105

Answers (2)

anubhava
anubhava

Reputation: 785108

You can pass your input to a function and make use of $@ to build your array:

makearr() { arr=( "$@" ); }

makearr foo bar hello world
# examine the array
declare -p arr
declare -a arr='([0]="foo" [1]="bar" [2]="hello" [3]="world")'

# unset the array
unset arr

makearr foo bar 'hello world'
# examine the array again
declare -p arr
declare -a arr='([0]="foo" [1]="bar" [2]="hello world")'

Upvotes: 0

chepner
chepner

Reputation: 531085

Specify a delimiter other than whitespace for the call to read:

$ IFS=, read -a array   # foo,bar,hello world
$ printf '%s\n' "${array[@]}"
foo
bar
hello world

You should probably be using the -r option with read, but since you aren't, you could have the user escape their own spaces:

$ read -a array    # foo bar hello\ world

Upvotes: 1

Related Questions