Generate unique user id with each addition of data

As I add new data to database.txt I want to generate a unqiue User Id. This is my current solution.

echo $RANDOM:$lname:$fname >> database.txt

But I seem to have problems when I try and use $RANDOM for formatting like so:

grep "^4539" database.txt | awk -F":" '{print "User ID:\t"$RANDOM"\nLast Name:\t" $lname"\nFirst Name:\t"$fname}'

How can I generate a unique user id another way. Where the variable can be used for piping and formatting?

  • How long can this unique user id be?
  • In one of my scripts, I had used the following to generate a unique string. See if this helps:
USER_ID="user`date +%Y%m%d%H%M%S`"

Of course, if you were to use the variable USER_ID more than once within a second, then this would fail.

Sounds good. Calling that variable would simply require a $USER_ID correct?

Try

grep "^4539" database.txt | awk -F":" -vRAND=$RANDOM '{print "User ID:\t"RAND"\nLast Name:\t" $lname"\nFirst Name:\t"$fname}'

If you want to use any variables inside awk, you will need to pass them...
Try this to get the usage...

awk -v arg=$RANDOM 'BEGIN{print arg}'

Also, use of grep is not required when you can achieve the same with awk!

awk '/^4539/{...}' input_file

HTH
--ahamed