Lbj_x
Lbj_x

Reputation: 415

Bash: read one column from one file and divided by one column in current file

I want to use bash to read one column from one file and divided by one column in current file and replace the column.

for example, I have one file called input.txt

1 2 3
1 4 3
1 8 3

And I want to read second column of the file and divide with 3rd column of current file aim_file.txt:

1 1 4
3 4 8
8 8 16

So I got result.txt:

1 1 2
3 4 2
8 8 2

Upvotes: 0

Views: 53

Answers (1)

anubhava
anubhava

Reputation: 785128

Using awk you can do:

awk 'NR==FNR{a[FNR]=$2; next} a[FNR]{$3 /= a[FNR]} 1' input.txt aim_file.txt

Output:

1 1 2
3 4 2
8 8 2
  • We first iterate input.txt and store the 2nd column in an associative array by index of line#
  • Next while iterating aim_file.txt we divide 3rd column with the value stored in array

Upvotes: 2

Related Questions