AWK - Add variable and result of function to variable

1

I want to add variable and result of function in AWK. Input:

t t t t
a t a ta
ata ta a a

Script:

{
key="t"
print gsub(key,"")#<-it's work
b=b+gsub(key,"")#<- it's something wrong
}
END{
print b}#<-so this is 0

Output:

4
2
2
0#<-the last print

diego9403

Posted 2015-08-31T11:10:02.690

Reputation: 807

Answers

2

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 ts 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 ts 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}

Scott

Posted 2015-08-31T11:10:02.690

Reputation: 17 653

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

3

gsub doesn't just count the occurences, it actually replaces them. The first print statement you have in there (presumably for debugging) is breaking it.

Brandon Xavier

Posted 2015-08-31T11:10:02.690

Reputation: 161

So, there is some function, which only count matching text? – diego9403 – 2015-08-31T13:10:38.363

1Not that I'm aware of. I'd just do something like '{ key = "t"; x = gsub(key,""); print x; b=b+x; } – Brandon Xavier – 2015-08-31T13:17:38.360

1@BrandonXavier, you should put the correct code in your answer. – glenn jackman – 2015-08-31T13:51:39.107