Bash – Remove all occurrences of a specific character in string

To remove all occurrences of a specific character in a string in Bash scripting, you can use tr command, as shown in the following expression.

$ echo string | tr -d char

Example

In the following script, we take a string in str. We remove all the occurrences of character "l" in the string, and print the resulting string to output using echo.

example.sh

#!/bin/bash
 
string="helloworld"
char="l"
output=$(echo "$string" | tr -d "$char")
echo $output

Bash Version: GNU bash, version 5.2.15(1)-release (aarch64-apple-darwin22.1.0)

Output

sh-3.2# bash example.sh 
heoword
ADVERTISEMENT

Conclusion

In this Bash Tutorial, we learned how to remove all the occurrences of a specific character in given string using tr command.