By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,713 Members | 1,250 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,713 IT Pros & Developers. It's quick & easy.

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

Expert 100+
P: 392
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.
Apr 13 '08 #1
Share this Question
Share on Google+
1 Reply

radoulov
P: 34
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/
Apr 14 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.