$ 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