Reputation: 37
My problem is quite simple but I do not manage to solve it:
I have a string that looks like this:
-3445.51692 -7177.16664 -9945.11057
the tricky part is that there could be zero or more withe space between each number and the latter can be either negative or positive, meaning that the string could also be like:
-3445.51692-7177.16664 -9945.11057
or
-3445.51692 7177.16664-9945.11057
(in case of a positive value there is at least one white space that precedes)
and I would like to split this string into three variables that contains each number, e.g.:
a=-3445.51692
b=-7177.16664
c=-9945.11057
Thus, I wanted to use something like
IFS=' -' read -a array <<< "$string"
but I don't know how to specify "zero or more white space". And using "-" as a delimiter removes it from the final result, while I want to keep the sign.
Any ideas ?
Upvotes: 2
Views: 253
Reputation: 785108
You can use read -a
by injecting a space first:
s='-3445.51692-7177.16664 -9945.11057'
IFS=' ' read -ra arr <<< "${s//-/ -}"
printf "[%s]\n" "${arr[@]}"
[-3445.51692]
[-7177.16664]
[-9945.11057]
Upvotes: 0
Reputation: 72639
Canonicalize the input before you do the IFS splitting, i.e. any minus gets a space prepended:
canonicalized_string=$(echo "$string" | sed 's/-/ -/g')
set -- $canonicalized_string # No need to mess with IFS.
a=$1
b=$2
c=$3
This assumes exactly 3 numbers. In super-compact form:
set -- $(echo "$string" | sed 's/-/ -/g')
a=$1 b=$2 c=$3
Upvotes: 1
Reputation: 27577
Simply use sed
to add a space infront of every -
, Something like:
echo $string | sed 's/-/ -/g'
Upvotes: 0