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 nothingOr, if you know what characters to keep:
myVar=${myVar/[^YS]} # Replace anything but Y or SOr, 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 CANTo remove all, use double slashes:
echo "${myVar//E}"
# YS W CANYou can replace not just a single character, but a long regex pattern. See more examples of variable expansion / substring replacement here.