简体   繁体   中英

Subtracting floating point numbers in a loop in bash

I have a file with 500 lines of floating point numbers. What I want to do is take a line, and then subtract every line lower in linenumber from that line. An example nonworking script would be:

for i in `seq 0 499`; do
       for ((j=0; j<i; j++)); do
               a=$(awk 'NR == i' i=$i inputfile)
               b=$(awk 'NR == j' j=$j inputfile)
               echo $(awk '{c=a-b};END{print c/NR}' a=$a b=$b)
       done
done > outputfile

I'm not familiar with how to use awk, so any help would be appreciated. Thank you!

Example:

input:

1
2
3
4
5

output:

1
2 - 1
3 - 1
3 - 2
4 - 1
4 - 2
4 - 3
5 - 1
5 - 2
5 - 3
5 - 4

Except instead of integers everything is a floating point number, and the subtractions should be evaluated

If you put this into a.awk

{
    a[NR] = $1
}
END {
    print a[1]
    for (i = 2; i <= NR; i++) 
        for (j = 1; j < i; j++) 
            print a[i]-a[j]
}

and run

awk -f a.awk foo.txt

You will get your desired output.

For example, if your input was

1.2
2.3
3.4
4.5
5.6

Your output would be

1.2
1.1
2.2
1.1
3.3
2.2
1.1
4.4
3.3
2.2
1.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM