I leave notes here that I find particularly worth remembering myself.
Shortest command to calculate the sum of a column of output
Posted 06-02-2010 at 06:27 AM by bittner
I had to calculate the Installed-Size for a .deb control file recently. Here is the solution I came up with:
What it does? The code tries to construct a calculation string and feeds it to the command line calculator bc as follows:
I have posted the same (or similar) solution on StackOverflow, by the way.
Enjoy!
Code:
dpkg-deb -c mypackage.deb | sed -e 's/.*root\s*//' -e 's/\s*2010-.*$//' | xargs | tr ' ' + | bc
- use dpkg-deb to get the file size information out of the Debian package
- sed away all characters before and after the number on each line (I could also sed away the 0 file sizes with an additional -e '/^0$/d', but that's optional from a mathematical point of view, obviously)
- xargs the result (to get a string of numbers separated by blanks)
- translate the blanks to '+' characters
- use bc to calculate the result
I have posted the same (or similar) solution on StackOverflow, by the way.

Enjoy!
Total Comments 2
Comments
-
Usually, bc should be installed on your Debian system. If you don't have it you could simply use a for loop that's built into bash:
Code:SUM=0; for i in $(dpkg-deb -c mypackage.deb | sed -e 's/.*root\s*//' -e 's/\s*2010-.*$//' | xargs | tr ' ' +); do SUM=$(($SUM+$i)); done; echo $SUM
Code:NUMBERS=$(dpkg-deb -c mypackage.deb | sed -e 's/.*root\s*//' -e 's/\s*2010-.*$//' | xargs | tr ' ' +) SUM=0; for i in $NUMBERS; do SUM=$(($SUM + $i)); done echo $SUM
Posted 06-02-2010 at 06:57 AM by bittner -
Calculate using Bash when bc is not installed
A much better alternative to bc than using a lengthy for loop is using Bash's calculation capability directly. Interestingly, I've figured out, there are two ways of assigning a value to a variable this way:- (( A=1+1 ))
- A=$(( 1+1 ))
Code:((SUM=$(dpkg-deb -c mypackage.deb | sed -e 's/.*root\s*//' -e 's/\s*2010-.*$//' | xargs | tr ' ' +)))
Code:SUM=$(($(dpkg-deb -c mypackage.deb | sed -e 's/.*root\s*//' -e 's/\s*2010-.*$//' | xargs | tr ' ' +)))
Posted 08-25-2010 at 03:12 AM by bittner