Search code examples
stringbashunique

Unique emails in string


I have a string with emails, some duplicated. For example only:

"[email protected],[email protected],[email protected],[email protected],[email protected]"

I would like string to contain only unique emails, comma separated. Result should be:

"[email protected],[email protected],[email protected]"

Any easy way to do this?

P.S. emails vary, and I don't know what they will contain.


Solution

  • How about this:

    echo "[email protected],[email protected],[email protected],[email protected],[email protected]" |
      tr ',' '\n' |
      sort |
      uniq |
      tr '\n' ',' |
      sed -e 's/,$//'
    

    I convert the separating commas into newlines so that I can then use tools (like sort, uniq, and grep) that work with lines.