Grouping hostnames for pdsh

Hi All,

I have a list of hostnames in a text file and I would like to craft a bash script that would group them for use with pdsh.

For example... I would like to group the following from a file:

hostname1000
hostname1001
hostname1002
hostname1003
hostname1004
hostname2000
hostname2001
hostname2002

into hostname[1000-1004,2000-2002]

I tried some prelimenary scripts like:

num=1;for a in $(cat range_hostname.txt |cut -c 1-12 |sort) ; do echo ${a}${num}; num=$[num+1 ];done

to get hostname10 , for example, and put a count after, but this just counts all the lines and puts the count at the end. Not like a group of like names like I need.

Any ideas for this?

Thanks!
Joe

the shell might not be the fittest tool. Try awk :

awk '
                {HN = $1
                 sub (/[0-9]*$/, _, HN)
                 sub (/^[a-z]*/, _, $1)
                }
NR == 1         {printf "%s[%d-", HN, $1
                }
NR > 1 &&
$1 != LAST+1    {printf "%d,%d-", LAST, $1
                }
                {LAST = $1
                }
END             {printf "%d]\n", $1
                }
' file
hostname[1000-1004,2000-2002]
1 Like

Thats great, RudiC!

Now I need to do some reading so I can figure out how it works :-D.

Thanks so much!
Joe

*Also, I will use code tags in future posts!

---------- Post updated at 10:02 AM ---------- Previous update was at 10:01 AM ----------

Oh, one more quick question on this...

How can I add number padding?

For example, if the hostname is

hostname0100
hostname0101
hostname0102

I would need to account for the zero before the '1'.

Thanks!
Joe

awk '
                {HN = $1
                 sub (/[0-9]*$/, _, HN)
                 sub (/^[a-z]*/, _, $1)
                }
NR == 1         {printf "%s[%04d-", HN, $1
                }
NR > 1 &&
$1+0 != LAST+1    {printf "%04d,%04d-", LAST, $1
                }
                {LAST = $1
                }
END             {printf "%04d]\n", $1
                }
' file
hostname[1000-1004,2000-2002,0100-0102]
1 Like

That did the trick!

Thanks a million!
Joe