Reputation: 99
I have a column of several rows like this:
20.000
15.000
42.500
42.500
45.000
45.000
50.000
50.000
50.000
50.000
50.000
50.000
50.000
50.000
50.000
and I need to end up with a file where:
first element is 20/2
second element is the previous value + 15/2
third element is the previous values + 42.5/2
an so on until the end
My problem is how to do the "loop".
Upvotes: 2
Views: 2340
Reputation: 67497
simply,
$ awk '{print v+=$1/2}' file
10
17.5
38.75
60
82.5
105
130
155
180
205
230
255
280
305
330
you can set printf
formatting if needed
Upvotes: 2
Reputation: 428
I think you might looking for for
loop
awk '{for (i = 1; i <= NF; i++) print temp = temp + $i/2 }' filename
remember one thing, i refers to a column number if you want to run this operation in only one column you can change value of
i = column number; i <= column number;
You can use this loop for complex scenario.
If you want to change the separator you can use parameter like -F and the separator.
awk -F ":" '{}' filename
Upvotes: 0
Reputation: 678
Try this:
awk '{prev += ($0) / 2; printf("%.3f\n", prev);}' a2.txt
Input:
20.000
15.000
42.500
42.500
45.000
45.000
50.000
50.000
50.000
50.000
50.000
50.000
50.000
50.000
50.000
Output:
10.000
17.500
38.750
60.000
82.500
105.000
130.000
155.000
180.000
205.000
230.000
255.000
280.000
305.000
330.000
Upvotes: 1
Reputation: 5252
I guess you need output to be one line:
awk '{s+=$1/2; out = out s " ";} END{print out}' file
#=> 10 17.5 38.75 60 82.5 105 130 155 180 205 230 255 280 305 330
There's an extra space at the end which I think has no harm.
You can remove it if you don't want it.
Upvotes: 0
Reputation: 241868
Perl to the rescue:
perl -lne 'print $s += $_ / 2' input-file > output-file
-l
removes newlines from input and adds them to output-n
reads the input line by line, executing the code for each$_
is the value read from each line/ 2
is division by 2+=
is the operator that adds its ride hand side to its left hand side and stores the result in the left hand side, returning the new value. I named the variable $s
as in "sum".Upvotes: 3