Thread: Adding in Unix

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2004
    Location
    Overseas - Azores
    Posts
    7
    Rep Power
    0

    Adding in Unix


    I've been thinking and cannot figure out a way to add a column of numbers in a file when each number I want is in a seperate line. For example, let's say the information below is my file:

    blah blah blah 456 324 554
    blah blah blah 567 234 987
    blah blah blah 456 324 534
    blah blah blah 456 224 554
    blah blah blah 456 344 554
    blah blah blah 456 324 544
    blah blah blah 456 325 554
    blah blah blah 456 324 554

    Ok, how would I add the fourth column in this file (first column of numbers)? I know how to sort from each column, and that's about all. So far, the man pages for sort, grep, wc, etc..., have not helped me. But, I don't know what other commands might help me better. Thanks for your help!
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jul 2004
    Location
    Middle Europa
    Posts
    1,198
    Rep Power
    17
    sort, grep, wc have nothing to do w/ your probl,
    sed, ed, vi, awk, perl or c are the friends for this.
    assumed the input is, like you say:
    >>>>> blah blah blah 567 234 987
    have a look what sed can:

    sed 's/\(.*\) \(.*\) \(.*\) \(.*\) \(.*\) \(.*\) /\1 \2 \3 aaaa\4 \4bbbbb \5 \6/' input>output

    try just for fun and read the manual pages
    feel free to optimize the code
    for filemanipulations not needing numerical computing or formating sed is the best.
    AND the same syntax works in ed, vi, awk, perl got a modern one, but should also support that.
    so learn once and reuse.
    Last edited by guggach; December 28th, 2004 at 12:40 PM. Reason: typo
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2003
    Posts
    121
    Rep Power
    14
    Try:
    awk '{x+=$4} END{print x}' file
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jul 2004
    Location
    Middle Europa
    Posts
    1,198
    Rep Power
    17
    sorry, i did not understand: (numerical) add.
    perderabo is OK.

IMN logo majestic logo threadwatch logo seochat tools logo