简体   繁体   中英

For loop through a file - multiple conditions

I got a file with two columns and want to write a for loop in bash which takes the value from the first column, subtracts 3 and multiplies it by the corresponding value in the second column. And then add all the values together.

The file looks for example like this:

1  3
2  5
7  8
4  30

then I want a loop which does:

1-3 * 3
+ 2-3*5
+ 7-3*8
+ 4-3*30

I have already a for loop which looks like this:

 for ( p in $( awk '{ print $1; }' file.txt ) 

 do

   total=$(echo $total+($p-3) | bc )
   ((count++))
 done

  echo " $total" | bc > file2.txt

This works. But what can I do to include a multiplication with another column of the file?

The following idea doesn't work:

for ( p in $( awk '{ print $1; }' file.txt ) && k in $( awk '{ print $2; }'       file.txt )).
awk '{ sum += $2*($1-3); } END{ print sum; }' <input file>

You have been given perfectly valid awk answer . But if you prefer to use bash , as long as you operate only in integer numbers, you can do everything in bash , without need to spawn awk or bc :

#!/bin/bash
sum=0
while read a b; do
    ((sum=sum+(a-3)*b))
done < file.txt
echo $sum

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