I’m having a problem with sed and single quotes
I have a string like this :
-cmd af -i 3 -a
I want to change this string to
-cmd 'af -i 3 -a'
Now I’m using this :
the string is stored in buff variable
buff=$(echo $buff | sed -r "s/cmd /CMD '/g")"'"
it echoes ok -cmd 'af -i 3 -a'
I then call a function with buff as a parameter and while executing the script with ksh -x I can see the call is NOK
+ buff=$'-CMD \'af -i 3 -a \''
+ echo -CMD $'\'af' -i 3 -a $'\''
-CMD 'af -i 3 -a' #this is the echo
+ functionTest -CMD $'\'af' -i 3 -a $'\''
As a result it will always give me
-CMD $'\'af' -i 3 -a $'\''
So basically it seems my single quotes are interpreted as $'\''
I have no idea why, I tried a lot of things such as escaping chars but it gives me the exact same result, even with \x27
How are you seeing the odd-ball result?
What you’ve got is OK in the raw (
sedon Mac OS X does not support-r, but the regex used doesn’t need the non-standard GNU extension option-ranyway):I suspect your problem is not in the transform, but in the way you’re viewing the result.
ksh test
The output is correct; the trace is slightly confusing but the same as what you show.
There is a good reason for the extra effort that the
-xoutput goes to; it disambiguates the output so that you can determine exactly what is what, if you can read it well enough. Also, you could copy’n’paste the line after the+and run it and get exactly the same result again. The old Bourne shell had a-xoption which did not do character mapping like this, and it could lead to confusion, and you certainly could not reliably copy’n’paste the trace output to execute the command again.The key point is that the result — what is echoed — is what you want and expect, so you’re fretting over nothing (as it happens). But I agree, it can be confusing at first.