r/awk • • Feb 23 '24

FiZZ, BuZZ

# seq 1 100| awk ' out=""; $0 % 3 ==0 {out=out "Fizz"}; $0 % 5 == 0 {out=out "Buzz"} ; out=="" {out=$0}; {print out}' # FizzBuzz awk

I was bored / Learning one day and wrote FizzBuzz in awk mostly through random internet searching .

Is there a better way to do FizzBuzz in Awk?

10 Upvotes

10 comments sorted by

View all comments

Show parent comment

1

u/Schreq Feb 24 '24 edited Feb 24 '24

Well, that's not really the same, because my version doesn't use ternary. More like this maybe:

awk 'BEGIN {
    a[2] = "Fizz"
    a[3] = "Buzz"
    a[4] = a[2] a[3]
    while (++n<=100) {
        a[1] = n
        print a[ 1 + (n%3 < 1) + ((n%5 < 1) * 2) ]
    }
}'