Search code examples
bashrandomalphanumericone-liner

Prevent final character from being a number


In bash, I run the following to get a random string:

LC_CTYPE=C tr -dc 'a-z0-9' </dev/urandom | fold -w 5 | head -n1

However, I need to make sure the last character is not a number.

What can I add to the command to do this, keeping it as a one-liner?

(I'd like it to be the same length, but if I have to trim it to 4 chars, so be it)


Solution

  • Use grep to select those lines that meet the criterion, and only then take the first one:

    LC_CTYPE=C tr -dc 'a-z0-9' </dev/urandom | fold -w 5 | grep '[^0-9]$' | head -n1
    

    By the way, echo $(x) is a nonsensical construct most of the time; you can just write x instead.