awk assign to multiple variables at once

Since you're using GNU awk, you can use the 3-arg form of match() to store multiple capturing groups:

awk '
    match($0, /([0-9]+)\.([0-9]+)/, m) {maj=m[1]; min=m[2]; print maj, min}
' <<END
tmux 2.8
tmux 1.9a
tmux 2.10
END
2 8
1 9
2 10

https://www.gnu.org/software/gawk/manual/html_node/String-Functions.html


Note that gensub is a gawk extension, it won't work with any other awk implementation. Also note that the + unary operator doesn't force numeric conversion in all awk implementations, using + 0 is more portable.

Here you could do:

tmux -V | awk -F '[ .]' '{maj = $2+0; min = $3+0; print maj, min}'

If you don't mind using GNU awk extensions, you could also do:

tmux -V | awk -v FPAT='[0-9]+' '{maj = $1; min = $2; print maj, min}'

You can split the version into an array:

awk '{ split($2, ver, /[.a-z]/) }'

then use ver[1] instead of maj, ver[2] instead of min.

Adding a-z to the separator removes any lowercase letter from the version number. (The other solutions are better here since they explicitly extract numbers.)

Tags:

Awk

Gawk