Search code examples
bashsedunzipbrackets

seeing the contents of a zipped file which contains square brackets


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?


Solution

  • 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