How to subtract a constant number from a column
Asked Answered
B

4

24

Is there a way to subtract the smallest value from all the values of a column? I need to subtract the first number in the 1st column from all other numbers in the first column.

I wrote this script, but it's not giving the right result:

$ awk '{$1 = $1 - 1280449530}' file 
1280449530 452
1280449531 2434
1280449531 2681
1280449531 2946
1280449531 1626
1280449532 3217
1280449532 4764
1280449532 4501
1280449532 3372
1280449533 4129
1280449533 6937
1280449533 6423
1280449533 4818
1280449534 4850
1280449534 8980
1280449534 8078
1280449534 6788
1280449535 5587
1280449535 10879
1280449535 9920
1280449535 8146
1280449536 6324
1280449536 12860
1280449536 11612
Bein answered 31/7, 2010 at 3:28 Comment(0)
P
30

What you have essentially works, you're just not outputting it. This will output what you want:

awk '{print ($1 - 1280449530) " " $2}' file

You can also be slightly cleverer and not hardcode the shift amount:

awk '{
       if(NR == 1) {
           shift = $1
       }

       print ($1 - shift) " " $2
}' file 
Presbyterian answered 31/7, 2010 at 3:32 Comment(0)
S
12

You were on the right track:

awk '{$1 = $1 - 1280449530; print}' file

Here is a simplified version of Michael's second example:

awk 'NR == 1 {origin = $1} {$1 = $1 - origin; print}' file
Sandasandakan answered 31/7, 2010 at 3:57 Comment(0)
C
1

bash shell script

#!/bin/bash

exec 4<"file"
read col1 col2<&4
while read -r n1 n2 <&4
do
  echo $((n1-$col1))
  # echo "scale=2;$n1 - $col1" | bc # dealing with decimals..
done
exec >&4-
Cowberry answered 31/7, 2010 at 4:6 Comment(0)
O
0

In vim you can select the column with and go to the bottom of the page with G then e to go to the end of the number then you may enter the number like 56 56 this will add 56 to the column

Overshoot answered 15/10, 2021 at 23:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.