0

I am working on a shell script that takes stdin or file as input and prints the averages and medians for rows or columns depending on the arguments.

When calculating the averages for the columns, the output needs to print out the following (tabbed):

enter image description here

My output currently looks like this (no spaces or tabs):

Averages:

92480654263

Medians:

6368974

Is there a way to echo out the averages and medians with tabs so each average and median set align left correctly? Here is a sample of how I am printing out the averages:

echo "Averages:"
        while read i
        do
            sum=0
            count=0
            mean=0
            #Cycle through the numbers in the rows
            for num in $i
            do
                #Perform calculations necessary to determine the average and median
                sum=$(($sum + $num))
                count=`expr $count + 1`
                mean=`expr $sum / $count`
            done
            echo -n "$mean"
        done < $1
2
  • Why are you using expr when you can (and do elsewhere) use $((...))? Commented Apr 22, 2017 at 22:04
  • off-topic: rename the variable i into line, that makes the code easier ti understand (calculate the mean for each line). Commented Apr 22, 2017 at 22:30

3 Answers 3

1

man echo:

   -e     enable interpretation of backslash escapes

   If -e is in effect, the following sequences are recognized:

   \t     horizontal tab

I'd try echo -n -e "$mean\t", didn't test it though.

Sign up to request clarification or add additional context in comments.

Comments

1

You should use printf. For instance, this will print a value followed by a tab

printf "%s\t" "$mean"

You can actually print several values separated by tabs if you want by adding arguments :

printf "%s\t" "$mean" "$count"

You can use an array expansion to print several values separated by tabs :

printf "%s\t" "${my_array[@]}"

Among advantages of printf over echo is the availability of flexible formatting strings, and the fact that implementations of printf vary less than those of echo among shells and operating systems.

Comments

0

You could try using column command but it does take additional steps:

echo "Averages:"

while read line
do
    sum=0
    count=0
    mean=0
    #Cycle through the numbers in the rows
    for num in $line
    do
        #Perform calculations necessary to determine the average and median
        (( sum += num ))
        (( count++ ))
        (( mean = sum / count ))
    done
    (( mean == 0 )) && out=$mean || out="$out|$mean"
done < $1

echo "$out" | column -s'|' -t

Above is untested as I do not have the original file, but you should get the idea. I would add that the division will also provide truncated values so not exactly accurate.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.