Search code examples
bashnumbersdelimited

Process a line of delimited numbers in bash


I have a line of numbers, and I want to be able to process them one by one. For ex.

3829 4837 3729 2874 3827 

I want to be able to get the sum, largest number, anything. But I'm not sure how to get each number to process it. I would REAAAAALLLLLLLLY like to stick with pure bash, I don't mind a convoluted solution in bash. But if awk is absolutely necessary I will use it. I don't want to use sed.

I think I could do something like:

max= cut -d" " -f1
in line L cut -d" " -f$(loop index) 
#check for max

I'm confused.

Edit: Thanks for your answers, I've seen some new things I've never seen in bash and I'm ready to explore them more. I received the info I sought and even more! :)


Solution

  • If you want to process process numbers one by one, taking advantage of shell word splitting :

    numbers="3829 4837 3729 2874 3827"
     for n in $numbers; do
         # do something with "$n"
    done
    

    SUM :

    numbers="3829 4837 3729 2874 3827"
    echo $((${numbers// /+}))
    

    or

    numbers="3829 4837 3729 2874 3827"
    for n in $numbers; do
         ((sum+=n))
    done
    
    echo $sum
    

    LARGEST :

    numbers="3829 4837 3729 2874 3827"
    for n in $numbers; do
         ((max<n)) && max=$n
    done
    
    echo $max
    

    Alternatively, if you want a global SUM with some shell tricks :

    $ tr ' ' '+' <<< '3829 4837 3729 2874 3827' | bc                                 
    19096 
    

    or

    $ awk '{$1=$1; print}' OFS=+ <<< '3829 4837 3729 2874 3827' | bc
    19096
    

    or

    $ echo  '3829 4837 3729 2874 3827' |
        awk '{for (i=1; i<=NF; i++) c+=$i} {print c}'
    19096