Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract columns then add new column by caculate in Linux

I have text file like below:

   ID   Grade1   Grade2  Grade3
 JK01       92       84      88
 JK02       87       80      93
 JK03       89       98      95

I want to extract specific column then add two column using awk.
Weight will from Grade2 *1.5+2,and Note is a specific number:17.
Desird Output like:

   ID   Grade2  Weight  Note
 JK01       84     134    17
 JK02       80     122    17
 JK03       98     149    17

I am using following command to achieve that

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

awk '{print $1,$3,$3*1.5+2, 17}' file.txt > file.tem.txt

But I got

ID Grade2 2 17
JK01 84 128 17
JK02 80 122 17
JK03 98 149 17

The header of Weight and Note not right.
And I also tried

awk -F, '{print $1,$3,"Weight", "Note"; next}
         {print $0,$2*1.5+2,17}' file.txt > file.tem.txt

form how to create column using awk with column name, still can’t get desird output.Any advice you can offer is appreciated.

>Solution :

check this out

awk 'BEGIN { OFS="\t" } NR==1 { print $1, $3, "Weight", "Note" } NR>1 { weight = $3 * 1.5 + 2; print $1, $3, weight, "17" }' file.txt

output

ID  Grade2  Weight  Note
JK01  84     128     17
JK02  80     122     17
JK03  98     149     17
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading