0

I have a requirement to embed single quotes in a string. How can I achieve via shell scripting?

Sample Input: --connect jdbc:sqlserver://XXXX:12;DatabaseName=S

Output: --connect 'jdbc:sqlserver://XXXX:12;DatabaseName=S'

The format of this will always remain same.

Yogesh
  • 47
  • 1
  • 10
  • If you know that the input will always start with `--connect `, just strip this part and wrap quotes around the rest. Or, split the input at the space (which also breaks it into `--connect` and *the rest*). In both cases, you can build the output together from these pieces, wrapping the second part in quotes. Or, replace the space by ` '` (space, quote) and append another single quote at the end. – user1934428 Apr 04 '19 at 11:58
  • Yes that's what I want, I am new to scripting, would you mind telling me how to achieve this? – Yogesh Apr 04 '19 at 12:00
  • Um, are you trying to add single-quotes so you can use it as part of a command? If so, don't do that; quotes are shell syntax, and will not be recognized in data (like variable values). See ["Variable containing multiple args with quotes in Bash"](https://stackoverflow.com/questions/7454526/bash-variable-containing-multiple-args-with-quotes) and [BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"](https://mywiki.wooledge.org/BashFAQ/050) Also, don't follow any suggestions that use `eval` -- it's a huge bug magnet. – Gordon Davisson Apr 04 '19 at 17:29
  • @Yogesh : I suggested 3 quite different alternatives. Which one do you want to approach? Edit your posting, so this can be discussed properly. Also show your own attempt into solving this. – user1934428 Apr 05 '19 at 04:48

2 Answers2

1

You can use the following :

echo "--connect jdbc:sqlserver://XXXX:12;DatabaseName=S" | sed "s| jdbc| 'jdbc|g;s|$|'|g"
Gautam
  • 1,862
  • 9
  • 16
  • I have to convert only a part of string to single quote and not whole quote. Out put is --connect 'jdbc:sqlserver://XXXX:12;DatabaseName=S'. The single quote starts with jdbc and not from --connect – Yogesh Apr 04 '19 at 11:45
0

you could also escape them :

var=\'hello\'
echo $var

Outputs 'hello'

nullPointer
  • 4,419
  • 1
  • 15
  • 27
  • I have to convert only a part of string to single quote and not whole quote. Out put is --connect 'jdbc:sqlserver://XXXX:12;DatabaseName=S'. The single quote starts with jdbc and not from --connect – Yogesh Apr 04 '19 at 11:45
  • Then just simply enclose it into double quotes as @Gautam suggested : `var="connect 'jdbc:sqlserver://XXXX:12;DatabaseName=S'"` – nullPointer Apr 04 '19 at 11:49
  • The original input will be: --connect jdbc:sqlserver://XXXX:12;DatabaseName=S with no quotes anywhere, not even at jdbc – Yogesh Apr 04 '19 at 11:52