awk processing of passed variables

Currently have this:

set current=192.168.0.5
set servicehost = `echo $current | awk -F. '{print $4}'`
echo $numberoffields

5

..but would like to reduce # of variables and eliminate echo to have something like this:

set servicehost = `awk -v s="$current" -F. 'BEGIN{print $2}'`

But doesn't work. In a similar vein how to determine NR and NF on variables passed via -v .. if possible. For example how to replace the following:

set string = "hello world"
set numberoffields = `echo $string | awk '{printf("%s\n",NF)}'`
echo $numberoffields

2

..with something like this:

set string = "hello world"
set numberoffields = awk -v s=$string 'BEGIN{printf("%s\n",NF)}'
echo $numberoffields

0

Would be great if it returned 2 somehow :slight_smile:

What shell is that?

In recent bash:

$ current=192.168.0.5
$ awk -v s="$current" -F. 'BEGIN{$0=s;print $2}'
168

and

$ awk -v s="$string" 'BEGIN{$0=s; printf("%s\n",NF)}'
2

Ahh "$0=var" is what's missing. Duh. Thank you!

# current=192.168.0.5
# eval set -- $(echo $current | tr '.' ' ')
# echo $1
192
# echo $2
168
# echo $3
0
# echo $4
5