Rashedul Islam
Rashedul Islam

Reputation: 939

How to multiply a column by array element in linux/awk

I have an array and want to multiply a column of a file with the array elements. But the multiplication with array element is not working.

Input.file

chr1    100    150    3.5
chr1    200    450    10.5
chr1    300    950    9.5
.....

Expected output

2
21
19
....

Code:

array=(2 3 4 5)

awk '{print $4*"${array[0]}"}' Input.file

My shell

echo $SHELL
/bin/bash

This multiplication returns all 0 values. What is the problem with my code?

Upvotes: 0

Views: 1087

Answers (2)

Jeff Y
Jeff Y

Reputation: 2456

OK, thanks for the update. You still haven't said which specific shell, but the problem is that everything inside the single quotes is awk-specific, so the array[0] in there is an awk variable (associative array), not the shell variable of the same name. Try getting the array reference outside of the single quotes; all you need to do is change those double-quotes to single quotes I think:

awk '{print $4*'${array[0]}'}' Input.file

To find your shell, you can use the ps command and look for processes whose names end in sh:

$ ps
      PID    PPID    PGID     WINPID   TTY     UID    STIME COMMAND
     2396       1    2396       2396  ?       197612   Oct 16 /usr/bin/mintty
     3480    2396    3480       3424  pty0    197612   Oct 16 /usr/bin/bash
     2500    3480    2500        224  pty0    197612 09:53:03 /usr/bin/ps

Common shell names are: ksh, sh, csh, bash. Mine is bash.

Upvotes: 1

karakfa
karakfa

Reputation: 67507

If you are using only one element of the array, you can pass it as a variable to your awk script

 awk -v s="${array[0]}" '{print s*$4}' input.file

Upvotes: 1

Related Questions