The problem with your code, as Brandon Xavier pointed out,
is that gsub
doesn’t just count matches; it actually replaces them.
So, for instance,
{
print
print gsub("t", "")
print
print gsub("t", "")
print
print "----------"
}
would print
t t t t
4
0
----------
a t a ta
2
a a a
0
a a a
----------
ata ta a a
2
aa a a a
0
aa a a a
----------
If you don’t care about corrupting your input data
(i.e., if counting the t
s is the only thing you want to do with them),
you can use Brandon’s suggestion:
{
x = gsub("t", "")
print x
b=b+x
}
END {print b}
The above is, arguably, the best answer,
inasmuch as it eliminates your redundant gsub
calls.
(The following approaches still use two calls to gsub
.)
If you want to avoid adding a new variable,
you can do so by making the substitution non-destructive:
{
key="t"
print gsub(key, key)
b=b+gsub(key, key)
}
END {print b}
i.e., replace the t
s with themselves,
so they’re still there when you do the second gsub
.
(You could also use gsub(key, "&")
to replace key
with itself.)
Another approach is to make the first gsub
modify something other than the actual input line:
{
temp=$0
print gsub("t", "", temp)
b = b + gsub("t", "")
}
END {print b}
Replace the 't's with themselves - so easy. I can't explain why I didn't think about this solution.I have to back to notes and bash. Thank you. – diego9403 – 2015-08-31T19:17:08.277