1755155 Members
4922 Online
108830 Solutions
New Discussion юеВ

AWK scripting question

 
SOLVED
Go to solution
Steve Sauve
Frequent Advisor

AWK scripting question

Hi everyone,
I'm attempting to automatically generate a new UID for a user created through my script. I'm attempting to do this by using awk to run through the /etc/passwd file, and set a variable to one higher than what it finds in field three (assuming field three is higher than the current value). I do realize there are a few ways of doing this without awk, but since I don't know awk that well(or at least didn't before starting this script :) I thought I'd try and use it.
The problem I'm actually having is how to get the final value of the variable out of awk and into the main script. If I print the variable inside of the awk statement I get the correct values, but if I echo the variable after the awk statement I get nothing. The following is my awk statement:

awk -F: '{if ($3 >= UID) { UID=$3; UID++;}}' /etc/passwd

Anyone have any ideas? Again I'd like to stick with awk if possible.

Thanks,
Steve
3 REPLIES 3
Rick Garland
Honored Contributor

Re: AWK scripting question

The following will work:

cat /etc/passwd | awk -F: '{if (($3 > UID)) print $3}' | sort -n | tail -1

This is going to awk out the UID field greater than some number UID. The sort will put into ascending order and the tail will grab the last line. To this, you can use the `expr` command and add 1 to the value to get a new UID number.
Stefan Schulz
Honored Contributor
Solution

Re: AWK scripting question

I would use something like:

ID = `your_awk_script` or
ID = $(your_awk_script)

After this ID should contain the value you print with you awk script. Inside you awk script i would put something like:

... END{print UID}

This should print the highest UID at the end of the awk script.

Let me know if this helped.

Regards Stefan
No Mouse found. System halted. Press Mousebutton to continue.
Steve Sauve
Frequent Advisor

Re: AWK scripting question

Thanks guys,
Although I believe either would have worked I went with the solution Stefan suggested. It was actually something I had tried, but I had neglected to put in the print statement (oops). Thank you both for your help.

Steve