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

In bash I have a string, and I'm trying to remove a character in the middle of the string. I know we can remove characters from the beginning or the end of a string like this:

myVar='YES'
myVar="${myVar#'Y'}"
myVar="${myVar%'S'}"

but how can I remove the one in the middle?

2 Answers

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
2

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like