I have the following bash code using gawk gsub:
replacedCount=$(gawk -v FILE_TMP="$FILE_TMP" -v OLD="$OLD" -v NEW="$NEW" '{ num += gsub( OLD, NEW ); print $0 > FILE_TMP; } END { print num }' "$FILE")
It replaces all instances of OLD with NEW and outputs the results to FILE_TMP - The number of replacements is caught in the bash variable.
Is it possible to achieve the same results using gawk gensub?
- $FILE is 182 lines long.
- There are 8 occurrences of $OLD that are to be replaced with $NEW
I've tried several ways, most results equal 182 as I guess I counting the number of occurrences of $0.
The closest I have got is this:
replacedCount=$(gawk -v FILE_TMP="$FILE_TMP" -v OLD="$OLD" -v NEW="$NEW" '{ num[$0=gensub( OLD, NEW, "G" )]++; print $0 > FILE_TMP; } END { for (i in num) print num[i] }' "$FILE")
Which does output to FILE_TMP correctly. However replacedCount is:
replacedCount='8
1
1
1
1
1
1
8
1
8
8
1
1
1
8
1
1
1
1
1
1
1
1
8
8
1
1
1
8
1
1
8
1
1
1
1
1
1
1
1
8
8
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
8
1
8
1
1
1
8
1
1
8
8
1'