Akshita
Akshita

Reputation: 49

Processing data from file in awk

I have a file as follows

  (-0.548,15.994)
  (1.008,8.91)
  (-0.19,4.594)
  (-0.99,9.99)

I used

 $ awk '{ mul = $1*$2; print mul }' input.txt > output.txt

But all the values of output.txt file are 0s. Can any one tell me where I am wrong

Upvotes: 1

Views: 43

Answers (3)

Akshay Hegde
Akshay Hegde

Reputation: 16997

awk can also have several separators, you just have to set field sep FS or -F wisely, thats enough, you can simplify you command like below

Input

$ cat f
 (-0.548,15.994)
  (1.008,8.91)
  (-0.19,4.594)
  (-0.99,9.99)

Output

$ awk -F'[(,)]' '{ print $2*$3 }' f
-8.76471
8.98128
-0.87286
-9.8901

Upvotes: 0

Martin
Martin

Reputation: 6687

shellter beat me be a few seconds with a better alternative, but here goes:

sed 's/[^0-9,\.-]*//g' input.txt | awk '{split($1,x,","); mul=x[1]*x[2]; print mul}' > output.txt

Upvotes: 2

shellter
shellter

Reputation: 37258

If you print the values of $1 and $2 you'll see the problem. You also need to tell awk to use , as a field seperator.

Here's a revised version of your code.

  awk -F, '{ gsub(/[()]/, "", $0); mul = $1*$2; print mul }' input.txt > output.txt

output

-8.76471
8.98128
-0.87286
-9.8901

IHTH

Upvotes: 1

Related Questions