Sunday, July 13, 2014

printf command could handle special character easily

Just found a better solution on handling special character in a string. In a given scenario where I have a loop to process each file from a given file list as shown below:
 while read file
 do
  newfile=$(echo "${file}" | sed 's, ,\\ ,g')
  ...
  ...

 done < ${TEMP_FILE}
Assuming ${TEMP_FILE} containing a list of files. The file is validate to see is there any space within the file name. If there is a space, prefix it with backslash. In this context, I was using sed command to handle this for me. But there is a problem where this command does not able to handle special character, such as single quote (‘) because this command only search for space and then prefix it with backslash.

I've been thinking to have all sed command for every single special characters but it seems not a wise move to me. The expert share me a though that printf command should help me out as shown in the code snippet below:

newfile=$(printf "%q" "${file}")

This solution not only fix the single quote but also space within a string. Really appreciate the help from expert.

No comments: