LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Adding array variables together (https://www.linuxquestions.org/questions/linux-newbie-8/adding-array-variables-together-707522/)

nobody123 02-25-2009 04:39 PM

Adding array variables together
 
Hi there! Thanks for taking the time to read this. Anyways, here is my problem.

I have inside a text file both characters and integers and I would like to add the integers together. I used the 'cut' command to extract the integers and assign the array to a variable called 'array'. This is how I did it:

Code:

array=$(cut -c52-53 file1)
echo $array

And the output of this is:
19 20 21 18 25 30 12 18 25 10

My question is how would I go about adding the integers together? I heard you would use a for loop but I just can't wrap my head around it. Any help is greatly appreciated.

FYI: I am programming in BASH

jschiwal 02-25-2009 05:30 PM

There are two forms of `for' that you can use.

for num in ${array[@]}; do
...
done

for (( i=0; i < ${#array[@]}; i++ )); do
..
done

When working with integers in bash, consider declaring the variable as an integer, and put parenthesis around arithmetic expressions. This can prevent the expression from being taken as a string.
e.g.
declare -i index=1
echo ${array[($index+1)]}

I've found this to be the case when a variable expansion like ${variable:(-8)}

nobody123 02-26-2009 04:43 PM

Quote:

Originally Posted by jschiwal (Post 3457473)
There are two forms of `for' that you can use.

for num in ${array[@]}; do
...
done

for (( i=0; i < ${#array[@]}; i++ )); do
..
done

When working with integers in bash, consider declaring the variable as an integer, and put parenthesis around arithmetic expressions. This can prevent the expression from being taken as a string.
e.g.
declare -i index=1
echo ${array[($index+1)]}

I've found this to be the case when a variable expansion like ${variable:(-8)}

Thanks for helping me again. I don't really know how to implement the code though. What I really am looking for was just adding the values in an array. Here's an example:

Code:

array = (2 5 7)
I was just wondering how to add the values of 2, 5, and 7 to make 14. Maybe I'm implementing your code wrong? :confused:


All times are GMT -5. The time now is 06:39 PM.