0

I have two files both with same number of rows. File1 has 16 columns and file2 has 2 column

file1

1 2 3 4...
2 3 4 5...
3 4 5 6...

file2

text 10
text 11
text 12

Now I want another file with following output

10 20 30 40...
22 33 44 55...
36 48 60 72...

I tried using awk but was not successful

1 Answer 1

0
$ awk '{ getline line <"file2"; split(line,a); for (i=1; i<=NF; ++i) $i *= a[2] };1' file1
10 20 30 40
22 33 44 55
36 48 60 72

For each line in file1, which is given on the command line, this awk program reads a line from file2 and splits it on the whitespace into the array a. The second element of a is used to multiply each field in the current record (from file1). At the end of the cycle, the trailing 1 causes the modified record to be outputted.

If the text in file2 contains whitespace, and if it's always the last field in that file that should be used, then keep track of how many fields the line string is split into:

$ awk '{ getline line <"file2"; nf=split(line,a); for (i=1; i<=NF; ++i) $i *= a[nf] };1' file1
10 20 30 40
22 33 44 55
36 48 60 72

To additionally avoid hard-coding the name of the second file, pass its name into an awk variable on the command line:

$ awk -v other=file2 '{ getline line <other; nf=split(line,a); for (i=1; i<=NF; ++i) $i *= a[nf] };1' file1
10 20 30 40
22 33 44 55
36 48 60 72

... or pass its name in an environment variable:

$ other=file2 awk '{ getline line <ENVIRON["other"]; nf=split(line,a); for (i=1; i<=NF; ++i) $i *= a[nf] };1' file1
10 20 30 40
22 33 44 55
36 48 60 72
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .