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.

1 Answer 1

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).

6
  • Not sure that I follow.. how can I use it within awk? Commented May 8, 2017 at 21:33
  • Tested and working. Appreciate it! One mini question, so I can not assign $IP variable with -v param? Commented May 8, 2017 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. Commented May 8, 2017 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! Commented May 8, 2017 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)). Commented May 8, 2017 at 21:53

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.