Using AWK to multiply a column in a file with float number

Using AWK to multiply a column in a file with float number

I need to multiply a column in a file with float numbers, say with (1.0 + 0.25)

I have a extracted column 3 ( with Numbers) with awk command from file file1.txt

awk '{ print $3 }' file1.txt > coloumn1

1.0  
1.2  
1.3  

I want to multiply all column values with (1.0 + 0.25)to achieve the following values. requirement is to use different p1 values. p1 is 1.1

( 1.0*(p1+0.25))  
( 1.2*(p1+0.25))  
( 1.3*(p1+0.25))  

1.250  
1.500  
1.625  

My script is

#bin/bash
p1=1.0
val=`echo $p1 + 0.25 | bc`
awk -F, '{$1*=$val}1' OFS=, coloumn1 > coloumn_mod

But above awk command is not returning the expected result ,

Could you please help correcting the above command ?

答案1

awk -v p1='1.0' '{ printf("%.3f\n", $0*(p1+0.25) ) }' infile

if there are more than a column in your input file and say they are separated by comma character and you want do this on 3rd column, you can use:

awk -F, -v p1='1.0' '{ printf("%.3f\n", $3*(p1+0.25) ) }' infile

in awk, $0 represents the entire record/line, $1 first field/column, $2 second field/column, $3 third field and so on; where fields splits on the default whitespace character (Tabs/Spaces) or you can redefine it by -F or -v FS= or within code-blocks as well.

相关内容