简体   繁体   English

对于文件循环-多个条件

[英]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. 我有一个包含两列的文件,想要在bash中编写一个for循环,该循环从第一列中获取值,然后减去3并将其乘以第二列中的相应值。 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循环,看起来像这样:

 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 . 您已获得完全有效的awk 答案 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 : 但是,如果你喜欢使用bash ,只要你只能在整数操作,你可以做的一切bash ,而不需要产卵awkbc

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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