0

This seems like a simple problem but I find everything command line confusing.

I have a CSV with 5 columns. I want to multiply everything in columns 2-5 by a variable defined earlier in my bash script.

Obviously the below doesn't work, but show's what I'm trying to achieve:

awk -F , -v OFS=, 'seq($2 $5)*='$MULTIPLIER in.csv > out.csv
Benjamin Allison
  • 2,134
  • 3
  • 30
  • 55
  • Good answers here on how to get your shell variable into your awk script (in your case `-v MULTIPLIER=$MULTIPLIER` and then you can use `MULTIPLIER` variable in your awk script. [How do I use shell variables in an awk script?](https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script) – JNevill Oct 21 '22 at 19:25

1 Answers1

2

Generally speaking:

awk -F, -v OFS=, -v m="${MULTIPLIER}" '{for (i=2;i<=5;i++) $i*=m}1' in.csv > out.csv

Assuming there's a header record, and a variation on setting FS/OFS:

awk -v m="${MULTIPLIER}" 'BEGIN {FS=OFS=","} NR>1 {for (i=2;i<=5;i++) $i*=m}1' in.csv > out.csv
markp-fuso
  • 28,790
  • 4
  • 16
  • 36
  • Thank you! That's brilliant. Bonus question: is there an easy way to round the result to the nearest integer? – Benjamin Allison Oct 21 '22 at 19:41
  • rounding in `awk` relies on the underlying libs available on your system (see [awk rounding function](https://www.gnu.org/software/gawk/manual/html_node/Round-Function.html) for more details); a web search on `awk rounding` will bring up a few different solutions; one idea (for this answer): `$i=int($i*m+0.5)`; though you'll need to think about how this would work for a negative value (eg, for `-3.5` do you want to round 'down' to `-4` or 'up' to `-3.5`) – markp-fuso Oct 21 '22 at 19:51