Looking for an easy way to add escape charaters to a string in BASH.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pronerd
    Recognized Expert Contributor
    • Nov 2006
    • 392

    Looking for an easy way to add escape charaters to a string in BASH.

    Hi,

    I was wondering if any one knows of an easy way to add escape characters to an existing string in a BASH script.

    I have a BASH script that is failing when a string is passed with brackets "[]" are passed to the sed command.

    I am trying to put together a BASH script to create Unix safe file names. i.e. Removes spaces, special characters, etc.


    This fails due to the brackets. It returns "/opt/content2/Transformers_Th e_Album/test blah[file].txt" instead of "/opt/content2/Transformers_Th e_Album"
    Code:
    somePath="/opt/content2/Transformers_The_Album/test blah[file].txt"
    highestLevel="test blah[file].txt"
    echo "$somePath" | sed "s/\/$highestLevel//g"
    
    Returns :  /opt/content2/Transformers_The_Album/test blah[file].txt


    If I manually escape the brackets "[]" then it works.

    Code:
    somePath="/opt/content2/Transformers_The_Album/test blah[file].txt"
    highestLevel="test blah\[file\].txt"
    echo "$somePath" | sed "s/\/$highestLevel//g"
    
    Returns :  /opt/content2/Transformers_The_Album


    I was wondering if anyone knew of an command, or other simple way to add the needed escape characters to a string. I was hoping to avoid having to create all of the logic to parse the string and add the characters as needed.
  • radoulov
    New Member
    • Jun 2007
    • 34

    #2
    Check the printf q option:

    Code:
    $ printf "%s" "$somePath" | sed "s_$(printf "%q" "$highestLevel")__g"
    /opt/content2/Transformers_The_Album/
    And perhaps you don't need sed:

    Code:
    $ printf "%s\n" "${somePath%/*}/"
    /opt/content2/Transformers_The_Album/
    Or (if you need to be specific):

    Code:
    $ printf "%s\n" "${somePath/$highestLevel}"
    /opt/content2/Transformers_The_Album/

    Comment

    Working...