Subtracting the value of a specific cell to the whole column
Dear all,
I'm looking for a command that could tell the program to subtract the numeric value of the first cell in a column to all the other values of the subsequent cells in that column. Please note that I need the command to be performed over several files - in which the value of the first cell always varies. Here is an example for alpha.txt file: 1 345 5678 1 452 3456879 1 234 45699 1 234 45699 .. The value in $3, first line (5678) should be subtracted to all the other values in the same column: $3 1 345 0 1 452 3451201 1 234 40021 1 234 40021 .. I'm playing around with awk but without succeeding.. I was also thinking to print that cell to anothr file and subtract it to all the others, but still: how do I select it? A double loop? Any advice is highly appreciated. All the best, Emiliano |
Hi,
Have a look at this: Code:
awk '{ if (NR == 1 ) { Value = $3 } { print $1, $2, $3 - Value } }' infile |
Hi druuna,
YES! It works beautifully.. I'm so grateful. I'm using a Mac terminal now, let's hope it will work tomorrow morning on my Linux machine.. Just one quick clarification: in this command the use of the built-in NR simply means that there is one single value to take into consideration, right? So adding a recurive option, the program would go all the way down the column? Thanks again and have a nice evening. Best, E- |
Yeah: basically NR > 1 would subtract each value to itself, all the way down.
|
Hi,
I think you already get it, but just to be sure: Code:
awk '{ if (NR == 1 ) { Value = $3 } { print $1, $2, $3 - Value } }' infile The green part is executed for all the records (all lines in this case). BTW: You're welcome :) Hope this clears things up a bit. |
I'll drop a Bash version:
Code:
#!/bin/bash use: Code:
./script < inputfile |
Ok Thanks Juako!
|
Do realize that the shell only does integer arithmetic though. If you have floating point numbers then you have to use awk.
|
Just for clarification, as the OP mentioned that there are several files, NR will only ever equal 1 for the first file read (or can be manually altered but we will
assume this is not going to happen). If the idea was to subtract the third column value from the first line in each file you will need to use FNR (this would also require some more finagling in the bash version) |
I'm just using a §{file} variable, and NR seems to work accordingly to the new file:
for file in alpha.txt beta.txt; do awk '{ if (FNR == 1 ) { Value = $3 } { print $1, $2, $3 - Value } }' ${file} done Best, E- |
And the for loop is why?
|
Quote:
Code:
#!/bin/bash |
This too might work: awk '(FNR==1){val=0+$3}{print $1 $2 $3-val}' <list of files> (Which is, I believe, the point of grail's question.)
|
Bingo :)
|
All times are GMT -5. The time now is 10:06 AM. |