Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hello
I have a range of servers which have a 3-digit identifier in their name (refer to input file below).
Not all of the numeric range is use i.e. the following do not exist:serv103
serv109$cat input
serv101
serv102
serv104
serv105
serv106
serv107
serv108
serv110I am attempting to write a script to identify the 3-digit identifiers NOT in use.
Desired output:
101:serv101
102:serv102
103:FREE
104:serv104
105:serv105
106:serv106
107:serv107
108:serv108
109:FREE
110:serv110My attempt so far has failed to print the free identifier and text "FREE".
I'm having problems with the else statement say for instance when id=103 or 109for i in `cat id` # range from 101-110
do
awk -v id=$1 '{num=sprintf("%s, substr($1,length($1)-2))
if(id==num) { printf("%s%s%s\n", id,":",$1) }
}' input
Can anyone assist or perhaps suggest a better approach?

Since my OS is Solaris, I'm using nawk. Also, there is no need to use sprintf:
#!/bin/ksh while read line do nawk -v id=$line ' BEGIN { xfree=0 } { num=substr($1,length($1)-2) if(id == num) { printf("%s:%s\n", id,$1) xfree=1 } } END { if(xfree == 0) printf("%s:FREE\n", id) } ' input done < id

Thank you user57, but I couldn't let this one go. This is a good example for using awk's associative arrays. I read the input file completely into an array and processed the id file in the main processing loop:
nawk ' BEGIN { while ( getline < "input" > 0 ) { num=substr($1,length($1)-2) arr[num]=$1 } } { if($1 in arr) printf("%s:%s\n", $1, arr[$1]) else printf("%s:FREE\n", $1) } ' id

nails,
Having already done the job I have just viewed your further post using awk's associative array.
An impressive solution! Once again thanks for taking the time to rely nails.

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |