0
x=`unzip -l "$i" | grep /config.xml | tail -1 | sed -e "s/.*:[0-9][0-9] *//"`
content=`unzip -c "$i" "$x" | DO MORE STUFF HERE

I am having a problem with the above command whenever x outputs a string with square brackets. For example, let's say that after running the x line, $x = "Refresher [Autosaved]/xml/config.xml". If I pass $x to the content line, I get an error that caution: filename not matched: Refresher [Autosaved]/xml/config.xml. I have tried updating the sed command to escape the brackets with s/\[\([^]]*\)\]/\\\[\1\\\]/g and the values echo out fine, but when I save it to x, the \[ and \] turns into just [ and ] and I am back to square one.

How can I run the content command if my x value has square brackets?

Shawn Dibble
  • 177
  • 2
  • 15
  • 1
    It would be a lot saner to use tools like the Python `zipfile` module that let you work directly with the names as literals, rather than trying to pick content out of a stream of text. – Charles Duffy Jul 31 '18 at 17:00

1 Answers1

2

Save yourself a ton of trouble using modern $(...) instead of legacy `...`. The former does not require additional escaping:

$ x=$(echo 'Foo [Bar].baz' | sed "s/\[\([^]]*\)\]/\\\[\1\\\]/g")
$ printf '%s\n' "$x"
Foo \[Bar\].baz


$ x=`echo 'Foo [Bar].baz' | sed "s/\[\([^]]*\)\]/\\\[\1\\\]/g"`
$ printf '%s\n' "$x"
Foo [Bar].baz
that other guy
  • 116,971
  • 11
  • 170
  • 194