add a new column of numbers to whitespace delimited data based on another column of numbers using Bash utilities

StackOverflow https://stackoverflow.com/questions/15066059

Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top