Search code examples
linuxbashlinux-mint

Bash check if user exists, if so add number to the username


If a username exists I have to add number 2 to that username, and if that username exists too I have to add number 3 to it and so on... (so if John exists the program has to add John2, and if he exists too, it has to add John3 etc.) Every user I add is then, of course, remembered.

What is the shortest and most simple way to do that in bash?


Solution

  • Suppose users.txt is:

    joe
    jimmy
    foo
    jimmy
    bar
    jimmy
    

    Then you can use awk

    awk 'cnt[$0]++{$0=$0 cnt[$0]-1} 1' users.txt
    

    to produce the output:

    joe
    jimmy
    foo
    jimmy1
    bar
    jimmy2