我正在尝试进行这样的计算,我有一个带有数字的文本文件,例如
459
455
463
Run Code Online (Sandbox Code Playgroud)
我必须计算这些数字相对于 600 的百分比。我的意思是
(459/600)*100这将是我的百分比,459从文本文件中获得。
有人可以帮我吗?
如果您的文件实际上只是一个数字列表,每行一个,请执行以下操作:
awk '{print $1,$1"%"}' numbers.txt
Run Code Online (Sandbox Code Playgroud)
或者,在sed:
sed -r 's/(.+)/\1 \1%/' numbers.txt
Run Code Online (Sandbox Code Playgroud)
好的,现在 questino 几乎完全改变了 ^^ 你现在需要计算给定的数字,它们相对于数字 600 代表了多少%。
这是一个修订版。
由于历史原因,我在下面给出了我的旧答案^^
awk ' { printf "%s %.2f%\n",$1,($1/600)*100; }' numbers.txt
Run Code Online (Sandbox Code Playgroud)
即,假设文件“numbers.txt”仅包含 1 列的数字介于 0 和 600 之间,它只打印数字,并在下一列中显示它相对于 600 的 %。我可以将第二个计算简单化为( $1/6)"%" 但在我看来,它会从脚本中删除重要信息。
在您的新示例数据上,它现在输出:
459 76.50%
455 75.83%
463 77.17%
Run Code Online (Sandbox Code Playgroud)
如果你真的需要计算百分比,那么它会是这样的:
awk '
{ # each line is read and stored, and the sum is computed also.
original[NR]=$0 ; #store the current line (line NR) in the "original[]" tab
sum+=$1 ; #and compute the sum of the 1st column
}
END { #at the END, ie after we processed the whole file
for(line=1;line<=NR;line++)
{ printf "%s %.2f%\n",original[line],original[line]/sum*100 ;
}
} ' numbers.txt
Run Code Online (Sandbox Code Playgroud)
这样的事情应该计算 % 并将其放在数字旁边(带有 2 个小数位)
在您给定的示例中,它输出:
12 5.36%
23 10.27%
35 15.62%
67 29.91%
87 38.84%
Run Code Online (Sandbox Code Playgroud)
$ paste -d' %' numbers.txt numbers.txt /dev/null
12 12%
23 23%
35 35%
67 67%
87 87%
Run Code Online (Sandbox Code Playgroud)
-d switch 需要多个分隔符:此处为空白和百分比