Share your knowledge at the LQ Wiki.
Go Back > Blogs > Notes on Linux
User Name


I leave notes here that I find particularly worth remembering myself.
Rate this Entry

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:

dpkg-deb -c mypackage.deb | sed -e 's/.*root\s*//' -e 's/\s*2010-.*$//' | xargs | tr ' ' + | bc
What it does? The code tries to construct a calculation string and feeds it to the command line calculator bc as follows:
  1. use dpkg-deb to get the file size information out of the Debian package
  2. 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)
  3. xargs the result (to get a string of numbers separated by blanks)
  4. translate the blanks to '+' characters
  5. use bc to calculate the result

I have posted the same (or similar) solution on StackOverflow, by the way.

Posted in Uncategorized
Views 7867 Comments 2
« Prev     Main     Next »
Total Comments 2


  1. Old Comment
    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:

    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
    Or probably easier to read:
    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
    You will notice that this takes a while, because the for loop is slow. Here, stripping out the 0-value lines may make sense...
    Posted 06-02-2010 at 06:57 AM by bittner bittner is offline
  2. Old Comment

    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 ))
    The spacing after and before the double-brackets is optional. The above calculation exercise would then read like this:

    ((SUM=$(dpkg-deb -c mypackage.deb | sed -e 's/.*root\s*//' -e 's/\s*2010-.*$//' | xargs | tr ' ' +)))
    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 bittner is offline


All times are GMT -5. The time now is 02:19 AM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration