Replace "[" with [ using sed

Asked

Viewed 841 times

1

I am trying to fix some formatting errors of a file and have as input:

"[""teste""]"

And I wanted to get an output like:

["teste"]

I’ve tried this command but it makes me wrong:

sed -i s/"["/[/g *.csv
sed -i s/"]"/]/g *.csv

The error shown is as follows::

sed: -e expressão #1, caractere 7: Comando `s' inacabado (s/// - faltou delimitador)

Can someone help me?

2 answers

2

It’s full of little problems in your line of code.

  1. The argument passed to is being interpreted by , which may result in unexpected effects
  2. [ is the list metacharacter (or linked list if used in conjunction with ^, and he’s not escaped
  3. The same for ]

Correction

sed 's/"\([][]\)"/\1/g'

Explaining:

  1. The argument is protected against any interpretation of for it is among apostrophes
  2. [][] is the list that includes the characters [ and ]; this is due to a special list syntax, ] can be placed as the first character of the list that will be interpreted like this, not as closing the list, so []a] would be the list containing ] and a
  3. \( is indicating the presence of a group; the traditional does not interpret ( as group metacharacter; could also have linked the expanded interpretation of regular expressions, but I don’t remember if it is -e or -E
  4. \) is the closing of the group
  5. \1 is the rear view mirror, use what was found in the number group 1, as we have only one group, and that group is composed of the list [][], that means it’s the character [ or the character ]

See working in:

DESKTOP-NLIG01H+Jefferson Quesado@DESKTOP-NLIG01H MINGW32 ~
$ echo '"[""teste""]"' | sed 's/"\([][]\)"/\1/g'
["teste"]

Print to prove the point:

print para demonstração

  • I am in windows and the use of ' does not work, I used the command you suggested and the output was the same as the input

  • But you marked [tag:bash], and the quote simply works with bash. Windows independent or not

0

Test there

sed -e 's/^"\["/[/' -e 's/"]"$/]/' *.csv

Browser other questions tagged

You are not signed in. Login or sign up in order to post.