Linux Bash ottenere la somma di numeri interi da file linea per linea
Due righe di codice bash per sommare insieme piu’ numeri all’interno di un file.
Prendiamo un file del tipo:
3443535
9878977
67554
987798
232324
Come ottenere la somma totale di tutte le linee? Niente di piu’ semplice:
#!/bin/bash
if [ -z $1 ]; then
echo “Usage: $0 <file>”
exit 1
fi
sum=`(sed ’s/^/x+=/’ $1; echo x) | bc`
echo $sum
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.


22:42 on December 23rd, 2007
Thanks. Very interesting post
23:54 on November 30th, 2007
interessante, più che altro da integrare con altro, tipo output di altri programmi (come un ‘grep ^ -c *’)
16:59 on November 30th, 2007
[...] I’m addicted to puns. :) This is a note for me, you and Michele: do you want to get the sum of a set of integers? Try this one [...]