bashshellbrackets

Replace/remove literal square brackets in Bash string


I am looking for a solution to eliminate square brackets in a Bash string. For instance, consider the string:

ldr r3, [r0,#8]! 

However I am not sure how to eliminate the '[' and ']'. I would like to eliminate all symbols in the most elegant way possible, such as:

str="ldr r3, [r0,#8]!"
echo ${str//[,.!]/}

but with square brackets inclusive. How can this be accomplished?


Solution

  • Use

    echo "${str//[][,.!]}"
    

    Because [] is not a useful pattern, the ] is treated as part of the bracket expression when it is the first character listed. Bracket expressions cannot be nested, so there is no restriction on the [.

    You can also simply escape the ]:

    echo "${str//[[\],.!]}"