Input and desired output:
a-b-c-d-e -> [a,b,c-d-e]
a-b-c -> [a,b,c]
abd-der-asd-d -> [abd,der,asd-d]
a-b -> throw error
Currently I am doing as such:
arr = ($(echo "$stringVar" | tr '-' '\n'))
But this splits on all '-' instances; I am trying to replicate only for the first two '-' characters.
Any suggestion on how this can be done, using only bash functions?
CodePudding user response:
Use read
to read the input into 3 variables. This will split out the first two items, and keep the rest as a single value.
input=a-b-c-d-e
IFS=- read -r item1 item2 rest <<<"$input"
if [ -z "$rest" ]
echo "Error"
exit 1
fi
array=("$item1" "$item2" "$rest")