I am trying to remove characters from a string variable. It works for me with sed like this:MYVAR=--23ho02123ware38384you443d34o3434ingtod38384day-%*#sfrfecho ${MYVAR} | sed -e 's/[a-z][a-z0-9\-]*//g'and I get: --23%*#which is what I am looking for. The string should start with a letter and contain only letters, digits, and a dash (-).Is there a way to achieve this with bash string replacement?MYVAR=${MYVAR/[a-z][a-z0-9-]*/ }I tried several combinations, but none of them work as I expected.
How to replace a substring from a variable?
bash;string
You'd need to use the ksh extended glob operators (a subset of which is available in bash with shopt -s extglob and with zsh with set -o kshglob) to get the equivalent of regular expressions (though with a different syntax: *(x) for the equivalent of x* here):shopt -s extglob # for bash# set -o kshglob # for zshprintf '%s\n' ${MYVAR//[[:alpha:]]*([[:alnum:]-])/}Or with zsh extendedglobs where the equivalent of regexp * is #:set -o extendedglobprintf '%s\n' ${MYVAR//[[:alpha:]][[:alnum:]-]#}A few notes:${var/pattern/replacement} replaces only the first occurrence. Use ${var//pattern/replacement} to replace every occurrence (like with the g flag in sed's s command).you had made your replacement a space character. Use ${var//pattern/} (or ${var//pattern}) to replace with the empty string.You don't want to use echo to output arbitrary stringsExcept in zsh, variable expansions in list contexts have to be quotedthe behaviour would be different compared to your sed approach when the variable contains newline characters.[a-z] matches characters (collating elements in some tools) comprised between a and z, the list of which varies with the locale, the system and the tool (for instance [a-z] with bash-4.3 in a en_GB.UTF-8 locale on a GNU system matches A, X, , , but not Z). That generally includes the 26 lower case letters of the English alphabet but not necessarily. [[:alpha:]] includes characters (or collating elements) that are considered alphabetical (regardless of case) in your locale. If you only want to match the 26 English letters, either use [abcdefghijklmnopqrstuvwxyz] or fix the locale to C (LC_ALL=C) and use [a-z] or [[:lower:]] for lower case English letters only or [a-zA-Z]/[[:alpha:]] for any English letter.[a-z0-9\-] in sed does match the backslash character, use [a-z0-9-] instead (the - has to be first or last to be taken literally).