1

I wanted to add 100 to the insertions, tried below, but it is adding $1 to it instead ?

#!/bin/bash
change_summary="17 files changed, 441 insertions(+), 49 deletions(-)"
lines_added="100"
echo $change_summary
echo $change_summary | awk '{ print $1 " " $2 " " $3 " " $4+$lines_added " " $5 " " $6 " " $7}'

it prints

17 files changed, 441 insertions(+), 49 deletions(-)
17 files changed, 458 insertions(+), 49 deletions(-)

I am expecting it to print 541 insertions.

is there a better way to do the same?

Jens
  • 69,818
  • 15
  • 125
  • 179
rodee
  • 3,233
  • 5
  • 34
  • 70

2 Answers2

2

Use an awk variable (tested with GNU awk):

 awk -v l=$lines_added '{ print $1 " " $2 " " $3 " " $4+l " " $5 " " $6 " " $7}'

or even more succinctly:

 $ echo $change_summary | awk -v l=$lines_added '{ $4 += l; print}'
 17 files changed, 541 insertions(+), 49 deletions(-)
Jens
  • 69,818
  • 15
  • 125
  • 179
  • thanks, I am using your second command, I also need to add number to $6, I tried `echo $change_summary | awk -v l=$lines_added d=$lines_deleted '{ $4 += l $6 +=d; print}'` it throws error, obviously I am making some mistake. any help? thanks a lot. – rodee Aug 19 '15 at 15:25
  • @Krish You need to use `-v` for each variable: `awk -v a=x -v b=y ...` and semicolons between each `$x += y` statement. – Jens Aug 19 '15 at 16:36
  • Nice! Note saying `print $1 " " $2`, etc is a bit unnecessary. Just say `print $1, $2` since the default output field separator is the space. – fedorqui Aug 20 '15 at 10:35
0

You should "unquote" the $lines_added:

~$ echo $change_summary | awk '{ print $1 " " $2 " " $3 " " ($4)+'$lines_added' " " $5 " " $6 " " $7}'
`17 files changed, 541 insertions(+), 49 deletions(-)

Since it's a bash variable, not a awk one.

fredtantini
  • 15,966
  • 8
  • 49
  • 55