Connecting Tech Pros Worldwide Help | Site Map

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

Expert
 
Join Date: Nov 2006
Posts: 392
#1: Apr 13 '08
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_The_Album/test blah[file].txt" instead of "/opt/content2/Transformers_The_Album"
Expand|Select|Wrap|Line Numbers
  1. somePath="/opt/content2/Transformers_The_Album/test blah[file].txt"
  2. highestLevel="test blah[file].txt"
  3. echo "$somePath" | sed "s/\/$highestLevel//g"
  4.  
  5. Returns :  /opt/content2/Transformers_The_Album/test blah[file].txt
  6.  
  7.  


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

Expand|Select|Wrap|Line Numbers
  1. somePath="/opt/content2/Transformers_The_Album/test blah[file].txt"
  2. highestLevel="test blah\[file\].txt"
  3. echo "$somePath" | sed "s/\/$highestLevel//g"
  4.  
  5. Returns :  /opt/content2/Transformers_The_Album
  6.  


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's Avatar
Member
 
Join Date: Jun 2007
Posts: 34
#2: Apr 14 '08

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


Check the printf q option:

Expand|Select|Wrap|Line Numbers
  1. $ printf "%s" "$somePath" | sed "s_$(printf "%q" "$highestLevel")__g"
  2. /opt/content2/Transformers_The_Album/
And perhaps you don't need sed:

Expand|Select|Wrap|Line Numbers
  1. $ printf "%s\n" "${somePath%/*}/"
  2. /opt/content2/Transformers_The_Album/
Or (if you need to be specific):

Expand|Select|Wrap|Line Numbers
  1. $ printf "%s\n" "${somePath/$highestLevel}"
  2. /opt/content2/Transformers_The_Album/
Reply