Saturday, July 12, 2014

Unix Shell: Merge User Accounts(2)

3. Create list of in-use user ids
terminal:
1) Print out the file of merge1's content
2) Use ":" as the field separator, print out the 3rd field(user id field), with merge1 as the input
3) Give the output of last step to sort command, to sort all records by number(-n option) and remove repetitive user ids(-u option), write the output to unique_ids file
4) List the unique_ids file
5) Print out the content of unique_ids file
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ cat merge1  
 xx1:pw1:1  
 xx2:pw2:1  
 xx3:pw3:2  
 xx3:pw3:3  
 xx4:pw4:4  
 xx:pw1:0  
 xx:pw1:0  
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ awk -F: '{print $3}' < merge1  
 1  
 1  
 2  
 3  
 4  
 0  
 0  
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ awk -F: '{print $3}' < merge1 | sort -n -u >unique_ids  
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ ls -lrt unique_ids  
 -rw-rw-r-- 1 aubinxia aubinxia 10 Jul 12 17:49 unique_ids  
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ cat unique_ids  
 0  
 1  
 2  
 3  
 4  

4. Given list of in-use user ids, generate a new un-used user id
newuid:
 #! /bin/bash  
   
 count=1  
   
 #Get the count option, to decide how many user ids  
 #we need to generate  
 while getopts "c:" opt  
 do  
   case $opt in  
   c) count=$OPTARG ;;  
   esac  
 done  
   
 shift $(($OPTIND - 1))  
   
 #IDFILE is the file containing all in-use user ids  
 IDFILE=$1  
   
 awk -v count=$count '  
 BEGIN {  
   # Read in all in-use ids and save those ids into  
   # array uidlist  
   for(i=1; getline id > 0; i++)  
   {  
     uidlist[i]=id  
   }  
   
   totalids=i  
     
   # Starting from the 2nd id, check if it is different from  
   # previous id, if yes, then try to pick up all un-used ids  
   # in between.  
   for(i=2; i<totalids; i++)  
   {  
     if(uidlist[i-1]!=uidlist[i])  
     {  
       for(j=uidlist[i-1]+1; j<uidlist[i];j++)  
       {  
         print j  
         if(--count == 0)  
           exit  
       }  
     }  
   }  
   
   # If we still do not get enough user ids, then we  
   # start from the last user id in array, until getting  
   # enough user ids  
   
   if(count != 0)  
   {  
     nextuid=uidlist[totalids-1]+1  
     while(count != 0)  
     {  
       print nextuid  
       nextuid++  
       count--  
     }  
   }  
 }' $IDFILE  

terminal:
1) Print out unique_ids file content, which is generated in last step
2) Use newuid script to generate 3 un-used new user ids based on unique_ids
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ cat unique_ids  
 0  
 1  
 2  
 3  
 4  
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ ./newuid -c 3 unique_ids  
 5  
 6  
 7  

No comments:

Post a Comment