How to remove characters in the middle of a string in bash

If you know what character(s) to remove, you can use substitution in parameter expansion:

myVar=${myVar/E}  # Replace E with nothing

Or, if you know what characters to keep:

myVar=${myVar/[^YS]}  # Replace anything but Y or S

Or, if you know the position:

myVar=${myVar:0:1}${myVar:2:1}  # The first and third characters

To remove just the first character, but not the rest, use a single slash as follow:

myVar='YES WE CAN'

echo "${myVar/E}" 
# YS WE CAN

To remove all, use double slashes:

echo "${myVar//E}"
# YS W CAN

You can replace not just a single character, but a long regex pattern. See more examples of variable expansion / substring replacement here.

Tags:

Bash