0

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 ?

αғsнιη
  • 40,939
  • 15
  • 71
  • 114
Partha
  • 1
  • 1
  • 1
    Please note that the reason why `awk` doesn't return the expected result is that because in the single quotes `' ... '` in which you have enclosed the program (as is recommended), shell variables are not expanded. If you are interested to learn more about this (and the peculiarities of it), see [here](https://stackoverflow.com/q/19075671/12231187) on how to import shell variables into `awk`. – AdminBee Nov 19 '20 at 09:37
  • 4
    Does this answer your question? [Use a shell variable in awk](https://unix.stackexchange.com/questions/50044/use-a-shell-variable-in-awk) – thanasisp Nov 19 '20 at 23:53

1 Answers1

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.

αғsнιη
  • 40,939
  • 15
  • 71
  • 114