¿Cuál es la forma más rápida de obtener la media de un conjunto de números desde la línea de comandos?

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

Pregunta

Usando cualquier herramienta que esperaría encontrar en un sistema nix (de hecho, si quiere, msdos también está bien), ¿cuál es la forma más fácil / rápida de calcular la media de un conjunto de números, suponiendo que ¿los tiene uno por línea en un flujo o archivo?

¿Fue útil?

Solución

Awk

awk '{total += $1; count++ } END {print total/count}'

Otros consejos

awk ' { n += $1 }; END { print n / NR }'

Esto acumula la suma en n , luego se divide por el número de elementos ( NR = Número de registros).

Funciona para enteros o reales.

Utilizando Num-Utils para UNIX:

average 1 2 3 4 5 6 7 8 9
perl -e 'while (<>) { $sum += <*>; $count++ } print $sum / $count, "\n"';

En Powershell, sería

get-content .\meanNumbers.txt | measure-object -average

Por supuesto, esa es la sintaxis detallada. Si lo escribiste usando alias,

gc .\meanNumbers.txt | measure-object -a

Usando " st " ( https://github.com/nferraz/st ):

$ st numbers.txt
N      min   max    sum    mean  sd
10.00  1.00  10.00  55.00  5.50  3.03

Especifique una opción para ver estadísticas individuales:

$ st numbers.txt --mean
5.5

(DESCARGO DE RESPONSABILIDAD: Escribí esta herramienta :))

Perl.

@a = <STDIN>;

for($i = 0; $i < #@a; $i++)
{
   $sum += $a[i];
}

print $a[i]/#@a;

Caveat Emptor: mi sintaxis puede ser un poco brusca.

Ruby one liner

cat numbers.txt | ruby -ne 'BEGIN{$sum=0}; $sum=$sum+

Ruby one liner

<*>

fuente

.to_f; END{puts $sum/$.}'

fuente

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top