Bash: How to Replace Special Characters in String


You can use the following methods to replace special characters in a string in Bash:

Method 1: Remove everything except letters

echo $my_string | sed "s/[^[:alpha:]]//g"

This particular example will remove all characters except letters from the string variable named $my_string.

Method 2: Remove everything except letters and numbers

echo $my_string | sed "s/[^[:alnum:]]//g"

This particular example will remove all characters except letters and numbers from the string variable named $my_string.

The following examples show how to use each method in practice.

Example 1: Remove Everything Except Letters in String in Bash

Suppose that we would like to use Bash to remove everything from a string except for alphabetical letters.

We can use the following syntax to do so:

$my_string="4P%enny$)~^Lane#-3!"
echo $my_string | sed "s/[^[:alpha:]]//g"

The following screenshot shows how to use this syntax in practice:

Bash remove special characters from string

Notice that all characters except for alphabetical letters have been removed from the string.

The original string was: 4P%enny$)~^Lane#-3!

The new string is: PennyLane

Example 2: Remove Everything Except Letters and Numbers in String in Bash

Suppose that we would like to use Bash to remove everything from a string except for alphabetical letters and numbers.

We can use the following syntax to do so:

$my_string="4P%enny$)~^Lane#-3!"
echo $my_string | sed "s/[^[:alnum:]]//g"

The following screenshot shows how to use this syntax in practice:

Bash remove all characters except numbers and letters

Notice that all characters except for alphabetical letters and numbers have been removed from the string.

The original string was: 4P%enny$)~^Lane#-3!

The new string is: 4PennyLane3

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Replace Text in String
Bash: How to Replace Specific Line in File
Bash: How to Replace Multiple Characters in String

Leave a Reply