Skip to content

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
Code language: Bash (bash)

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:]'
Code language: Bash (bash)

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

See also  Pad a string with zeros using PHP
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x