Remove Special Characters in a String using Bash

0 min read 148 words

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:].

Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags