简体   繁体   中英

Bash-parsing string into an array of floating point numbers

I wish to create an array of floating point numbers (called b) in BASH, the contents of the array is given by parsing the following variable adse :

echo $adse
16.92 18.29 19.18 20.87 2.78 2.88 2.77 2.83 2.80 2.78 2.73 2.73 2.75 2.93 2.91 2.93 2.77 4.64 2.67 3.01 6.78

so that b[1]=16.92; b[2]=18.29.....

How can I achieve this?

With

b=($adse)

you get a bash array b . Individual arguments can be accessed with ${b[index]} . Indices are zero-based, so the first element is ${b[0]} .

Be aware that you will find it difficult to do anything with these values in bash, though. It might be a good idea to use a scripting language that has support for floating point calculations, such as Perl or Python.

For a more in-depth discussion of bash arrays, see this link .

The canonical solution is:

read -r -d '' -a b <<<"$adse"

Unlike solutions which rely on default word-splitting of an unquoted expansion of $adse , the read built-in will not produce unwanted expansions of glob characters.

If you want to split the variable on some character other than whitespace, you can set IFS locally for the read :

IFS=: read -r -d '' -a b <<<"$adse"

That will not split on newlines. If you wanted to split on colon or newline, you could use IFS=$':\\n' .

Both of the above will set b[0] to the first element, not b[1] . If you wanted to start at b[1] , you could prepend 0 or some such to the input to read , and then unset "b[0]" afterwards.

help read to get an explanation of the options. Briefly, -r avoids interpretation of backslash escape sequences; -d '' causes the read to terminate at the end of input instead of the end of a line, and -ab causes the result to be placed in the array b .

Try with:

b=($(echo $adse))

But it begins with index 0, like:

echo ${b[0]}

that yields:

16.92

Although there is an easy solution to achieve what you want, I believe the following is also useful if, say, you have a string whose delimiters are not whitespace:

b=()
adse="16.92 18.29 19.18 20.87 2.78 2.88 2.77 2.83 2.80 2.78 2.73 2.73 2.75 2.93 2.91 2.93 2.77 4.64 2.67 3.01 6.78"

b=(${adse// / })

For example, if you had a string like this:

adse="16.92:18.29...etc"

You would have to change b=(${adse// / }) to:

b=(${adse//:/ })

However, for your particular case, all that is needed to parse the string into an array is already stated by Birei below.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM