Remove Special Characters in a String using Bash

Programming languages provide the ability to remove special characters from a string quite easily.

Sometimes you need to also do this from your command-line using Bash.

Let’s say we have a bash variable called USER_EMAIL and we want to remove any periods, underscores, dashes and the @ symbol, how would we go about this?

We could pipe our variable to a useful command called tr (which is the translate or delete characters tool) and strip these specifics before pushing the output back to a new bash variable.

USER_EMAIL="[email protected]"
NEW_USER_EMAIL=`echo $USER_EMAIL | tr -dc '[:alnum:]\n\r' | tr '[:upper:]' '[:lower:]'`

echo $NEW_USER_EMAIL

# yournameexamplecom

This is really powerful and pretty simple actually.

What about if you want to get rid of characters like \r \n or ^C from a variable?

OUT_VARIABLE=echo $IN_VARIABLE | tr -d '[:cntrl:]'

Your solution comes in the form of another -d or -delete argument called [:cntrl:].

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments