Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing variables to awk 1

Status
Not open for further replies.

kwasserman

Technical User
Oct 21, 2004
7
0
0
US
We have several large clients that have access to our UNIX system, and we set up their users within pre-defined user ID# ranges in /etc/passwd. I want to be able to find the highest user ID# used within a range and redirect the output to a temporary file (lastnum.tmp) for use in another script. To do this, I've created a reverse-sorted listing (passwd.sorted) of the USER ID# field cut out of the /etc/passwd file. The passwd.sorted file looks something like this:

...
3702
3701
3700 <- first number in range 3700 - 3999
3527 <- last number used in range 3500 - 3699
3526
3525
...

I have an awk routine that reads the passwd.sorted file, finds the last number used in a particular range, and passes this to the lastnum.tmp file:

awk '/^3700/ {getline;print $1}' passwd.sorted > lastnum.tmp
lastnum=$(cat lastnum.tmp)
echo "The last user ID is $lastnum"

The output: "The last user ID is 3527"

This works fine, but since we have about 8 user ID# ranges, I would rather declare the awk matching pattern through a variable, something like this:

firstnum="3700"
awk -v num=$firstnum '/^num/{getline;print $1}' passwd.sorted > lastnum.tmp

I've tried several ways to get this to work, but I either get an entire listing of the passwd.sorted file, or no output at all. What am I doing wrong?
 
What about this ?
awk -v num=$firstnum '$1==num{getline;print $1}' passwd.sorted > lastnum.tmp

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
$0 ~ ("^" num) ....

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top