1

I have a txt file " 80 50 65 100 2 35 1 " and i need to add each number in a Var or even better all of them in an array. like ...

var1=80 var2=50

or

array[0]=80

.by the way the number after that must be functional . I mean i need to be able to sum= $var1 +$var2 for example. Is there a way to do that ? Thank you!!

1
  • Are they all on one line or on multiple lines? Commented Nov 9, 2011 at 14:48

3 Answers 3

4

If your numbers are all on a line, use read

read -a array < numbers.txt

If they're on multiple lines you can change the end of line delimiter like this

read -d'\0' -a array < numbers.txt

And now you have an array

printf 'Number: %s\n' "${array[@]}"

Oh yeah, and summing. Lots of ways once you have an array, but how about

printf '%s + ' "${array[@]}" | xargs -I{} echo {} 0 | bc

Or do it all in one process

for n in "${array[@]}" ; do let sum+=$n ; done ; echo $sum
Sign up to request clarification or add additional context in comments.

2 Comments

the numbers in my file are in multiple lines so i used read -d'\0' -a array < numbers.txt . But when i try to print the array it does nothing...
To print an array, do echo "${array[@]}"
2

In bash, you can say

array=( $(< numbers.txt) )
sum=$( IFS=+; echo "${array[*]}" | bc )

Comments

1

So if you have a file nums.dat like

80 50 65 100 2 35 1

You can read these into an array with

read -a MYARRAY < nums.dat

If you have a much older bash or even ksh then it was something like (can't remember exactly sorry)

set -A MYARRAY $(cat nums.dat)

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.