0

I want to perform a simple calculation on each number in a column of whitespace delimited data using Bash utilities such as cut and bc. The data may look like something such as the following:

string 0.998663 string string string
string 0.998592 string string string
string 0.999096 string string string

Let's say I want to change the show the numbers in the second column to three significant figures. I want to add another column of these new numbers to this data directly following the second column. So, the result may look like something such as the following:

string 0.998663 0.999 string string string
string 0.998592 0.999 string string string
string 0.999096 0.999 string string string

I know that I can manually cycle through all of this data and then construct new columns of data, but I imagine that there is a more efficient way of doing this. Would you happen to know of some clever way of doing this?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
d3pd
  • 7,935
  • 24
  • 76
  • 127

2 Answers2

4

try this short line:

awk '$2=$2" "sprintf("%.3f",$2)' file

with your example data:

kent$  echo "string 0.998663 string string string
string 0.998592 string string string
string 0.999096 string string string"|awk '$2=$2" "sprintf("%.3f",$2)'
string 0.998663 0.999 string string string
string 0.998592 0.999 string string string
string 0.999096 0.999 string string string
Kent
  • 189,393
  • 32
  • 233
  • 301
1

You can try with:

awk '{printf("%s %s %.3f %s %s %s\n",$1,$2,$2,$3,$4,$5)}' file

Test

$ awk '{printf("%s %s %.3f %s %s %s\n",$1,$2,$2,$3,$4,$5)}' file
string 0.998663 0.999 string string string
string 0.998592 0.999 string string string
string 0.999096 0.999 string string string
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 2
    You don't need a loop here! `awk '{printf("%s %s %.3f %s %s %s\n",$1,$2,$2,$3,$4,$5)}' file` is enough. – dogbane Feb 25 '13 at 11:43
  • i am not sure if it is fast solution.. you started/stopped awk process linenumber times. – Kent Feb 25 '13 at 11:53