0

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"]
4
  • There is no different delimiter in foo bar `hello world` Commented Oct 6, 2016 at 19:05
  • @anubhava Thanks for the clarification. I didn't get any concrete definition on what a delimiter according to bash so I assumed to the best of my knowledge it was synonymous with a character used to split input. I edited my question. Commented Oct 6, 2016 at 19:08
  • 1
    Backtick is used for command substitution in BASH or POSIX. You probably can use single quotes like foo bar 'hello world' Commented Oct 6, 2016 at 19:09
  • Interesting, good to know. Commented Oct 6, 2016 at 19:10

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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")'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.