Richard Rublev Richard Rublev - 3 months ago 9
Linux Question

How to divide with awk?

I want to read file and divide all elements by 0.03.Precision is IMPORTANT.Then to save result in output file.

#!/bin/bash

var=$(cat 262_V01_C00_R000_TEx_BL_2048H.dat)
mapfile var < infile

awk '{for(i=1;i<=NF;i++) $i=$i*100/3}1' infile > output


But I got

a4.sh: line 4: infile: No such file or directory


Sample input

-9.341203692800e+02
-9.320539972800e+02
-9.302205617600e+02


Sample output

-31137.345
-31068.466
-31007.352

Answer

You can use this awk:

awk '$0+0 == $0 { printf "%.3f\n", $0 / .03 }' file
-31137.346
-31068.467
-31007.352
  • $0+0 == $0 will make sure to execute this division for lines with valid numbers only.
  • printf "%.3f" will print result with 3 precision points.
Comments