1

I am wondering, is possible to iterate over the last IP octet with awk, assuming that IP is a variable received from bash stdin, something like:

#!/bin/bash
read IP

awk -v IP="${IP}"  'BEGIN{FS="."} {for (i=1; i<=251; i++) { print $1 $2 $3 i } }'

And the output will be like:

192.168.1.1
192.168.1.2
....
192.168.1.251

Note that this won't work, but I hope you get the idea.

3
printf '192.168.1.%d\n' {1..251}

This will use the brace expansion of bash (originally a zsh feature, also available in ksh93) to generate numbers between 1 and 251, and for each number the printf will print an IP address with the number inserted at the end.

The following would read an IP address and do the same with that:

IFS='.' read a1 a2 a3 a4
printf -- "$a1.$a2.$a3.%d\n" {1..251}

If you'd wanted to use awk:

awk 'BEGIN { OFS = FS = "." } { for (i = 1; i <= 251; ++i) print $1, $2, $3, i }' <<<"$IP"

We want both the input and output field delimiter to be a dot, so we set both FS and OFS to this character in a BEGIN block. Then we read the IP addresses from standard input, and for each IP address we iterate from 1 to 251 and print out the list.

On the command-line we feed in $IP as a "here-string" (originally a feature of zsh, but also available in bash and ksh93).

  • Not sure that I follow.. how can I use it within awk? – fugitive May 8 '17 at 21:33
  • Tested and working. Appreciate it! One mini question, so I can not assign $IP variable with -v param? – fugitive May 8 '17 at 21:38
  • @fugitive Not really. Well, you could, but you would have to split it yourself with split() and do the output in the BEGIN block. Then you would have to use /dev/null as input since the program wouldn't actually need to read anything. – Kusalananda May 8 '17 at 21:40
  • I see, my first idea was to use split() and iterate over array, but that didn't work. Thank you for explanation sir! – fugitive May 8 '17 at 21:42
  • 3
    About credit. Both <<< and {1..251} are features that originated in zsh. (though <<< was inspired from a similar feature in the Unix port of rc, and {1..251} is reminiscent of perl's (1..251)). – Stéphane Chazelas May 8 '17 at 21:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.