简体   繁体   中英

How to handle whitespace in shell?

Input File

      name;x1;x2
    jon,doe;10;20
    sam,smith;11;21

This is what i have tried so far

awk 'BEGIN {print "name\tx1\tx2\tAvg"} {s+=$2} {k+=$3} {print $1,"\t",$2,"\t",$3,"\t",($2+$3)/2} END {print s/2,k/2}' input.txt

I am trying to find the average of rows and columns from an input file but at the end i am getting one zero that i don't need and i believe that is due to white space. Can someone help me how to handle white space here ?

The expected output should be :

name;x1;x2 Average 
jon,doe;10;20 15
sam,smith;11;21 16
Average 10.5 20.5

The default input field separator for awk is whitespace. That doesn't work for your file where the field separator is a semicolon. To fix that, use the -F\\; option. With a few other minor changes, try:

$ awk -F';' '{sub(/^ +/,"");} NR==1 {print $0, "Avg";next} {s+=$2} {k+=$3} {print $0,($2+$3)/2} END {print "Ave",s/(NR-1),k/(NR-1)}' OFS='\t' input.txt
name;x1;x2      Avg
jon,doe;10;20   15
sam,smith;11;21 16
Ave     10.5    20.5

The sample output in the question and as above has a mix of semicolons and whitespace for field separators. If you want to consistently use semicolons:

$ awk -F';' '{sub(/^ +/,"");} NR==1 {print $0, "Avg";next} {s+=$2} {k+=$3} {print $0,($2+$3)/2} END {print "Ave",s/(NR-1),k/(NR-1)}' OFS=';' input.txt
name;x1;x2;Avg
jon,doe;10;20;15
sam,smith;11;21;16
Ave;10.5;20.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM