I have a string:
['A', 'B']
I need to remove all ,, [, and ] characters. The final result should be
'A' 'B'
Below is a list of everything I tried, and the results
Commands I tried
user@vm:~$ echo "['A', 'B']" | sed -r 's/[\[\],]//g'
['A', 'B']
user@vm:~$ echo "['A', 'B']" | sed -r 's/[[],]//g' # unescaped
['A', 'B']
user@vm:~$ echo "['A', 'B']" | sed -r 's/[\[\]]//g' # removed ","
['A', 'B']
user@vm:~$ echo "['A', 'B']" | sed -r 's/[,]//g' #removed "[" and "]"
['A' 'B']
user@vm:~$ echo "['A', 'B']" | sed -r 's/[[,]//g' # removed "]"
'A' 'B']
Obviously, none of them worked. However, these commands did:
user@vm:~$ echo "['A', 'B']" | sed -r 's/[],[]//g'
'A' 'B'
user@vm:~$ echo "['A', 'B']" | sed -r 's/[][,]//g'
'A' 'B'
Why did this work? Differences between commands above and below:
[, ] are not escapedWhy does the order matter?
From info sed (see also https://www.gnu.org/software/sed/manual/sed.html#Character-Classes-and-Bracket-Expressions)
A leading '^' reverses the meaning of LIST, so that it matches any single character not in LIST. To include ']' in the list, make it the first character (after the '^' if needed), to include '-' in the list, make it the first or last; to include '^' put it after the first character.
And as mentioned in comments, tr is better suited
$ echo "['A', 'B']" | tr -d '[],'
'A' 'B'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With