0

This function works, but I am thinking there must be a more elegant way to convert all '/' to '\/' (so that I can subsequently feed it into sed using the standard '/' for substitute):

escapeslash() {
    val="$1"    
    fixed=""
    while [ 1 ]; do
        start=${val%%/*}
        remainder=${val#*/}
        if [ "${remainder}" = "${val}" ]; then
            fixed="${fixed}${start}"
            break;
        fi
        fixed="${fixed}${start}\/"
        val="${remainder}"  
    done    
    echo "${fixed}" 
}
mike
  • 819
  • 4
  • 14
  • What kind of strings you usually encounter? Provide a few samples! – Inian Jul 05 '19 at 05:15
  • as an example, if I do: `x=\`escapeslash "/tmp/file"`\` it will set x to: `"\/tmp\/file"` This is what I want so that i can subsequently call sed. My code does: `val=\`escapeslash "${val}"\`;error=\`echo "${error}" | sed "s/${delim}/${val}/"\` ` With this routine, I can be confident that sed will be 'happy' because I am escaping the '/' – mike Jul 05 '19 at 05:18
  • 1
    Simpler solution is to use alternative substitution delimiters, e.g. `sed "s#${delim}#${val}#"` – David C. Rankin Jul 05 '19 at 05:45
  • 1
    possible duplicate of https://stackoverflow.com/q/29613304/10971581 – jhnc Jul 05 '19 at 08:47
  • David - good idea but in my case I don't know what text will be in 'val' - and since it could have a # in it, that would just create a different problem. – mike Jul 05 '19 at 16:08
  • Thank you I0b0 and jhnc. That's what I was after. Never thought to use sed to fix the input to sed! – mike Jul 05 '19 at 16:17

0 Answers0