简体   繁体   English

如何在Shell中处理空格?

[英]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. awk的默认输入字段分隔符是空格。 That doesn't work for your file where the field separator is a semicolon. 这对于字段分隔符为分号的文件不起作用。 To fix that, use the -F\\; 要解决此问题,请使用-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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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