2

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 ?

2
  • does it have to be 'read'? Can you not for example use sed to parse the string? Commented Jan 30, 2015 at 14:54
  • You are right, sed is more appropriate here, like suggested in the answers. Commented Jan 30, 2015 at 15:20

3 Answers 3

1

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

2 Comments

Thanks :) ! I've got one question though, how does the "set" command replace the IFS method ? I mean according to what does it split the string ?
@Goujon The POSIX shell specification says that the default value for IFS is <space><tab><newline>. set doesn't do any splitting; it's simply the shell that performs word splitting according to IFS for any command.
0

Simply use sed to add a space infront of every -, Something like:

echo $string | sed 's/-/ -/g'

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.