Using parentheses inside a character class in a regex

I have a line:

['A', 'B']

      

I need to remove all characters ,

, [

and ]

. The end result should be

'A' 'B'

      

Below is a list of everything I've tried and the results

The commands I've 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 ran:

user@vm:~$ echo "['A', 'B']" | sed -r 's/[],[]//g'
'A' 'B'

user@vm:~$ echo "['A', 'B']" | sed -r 's/[][,]//g'
'A' 'B'

      

Why did it work? Differences between the commands above and below:

  • [

    are ]

    not shielded
  • The order is different (] to [)

Why does order matter?

+3


source to share


1 answer


From info sed

(see also https://www.gnu.org/software/sed/manual/sed.html#Character-Classes-and-Bracket-Expressions )

The leading "^" changes the LIST value to match any one character missing from the LIST. To include ']' in the list, make it the first character (after the "^" if necessary); to include the '-' in the list, make it first or last; include '^' put it after the first character.



And as mentioned in the comments, a tr

better fit

$ echo "['A', 'B']" | tr -d '[],'
'A' 'B'

      

+4


source







All Articles