Sed command with apostrophe

Solution 1:

$ sed -e "s/cluster_name: 'Test Cluster'/cluster_name: 'Test Cluster1'/"

or

sed -e 's/cluster_name: '\''Test Cluster'\'\/cluster_name:' '\'Test' 'Cluster1\'/

The one with all single quotes was more difficult to construct without this program to help, If you want some help getting the command correct, there is a C program you can use

$ cat w.c
#include <stdio.h>

int main(int argc, char *argv[]) {
        int i = 0;
        while (argv[i]) {
                printf("argv[%d] = %s\n", i, argv[i]);
                i++;
        }
        return 0;
}

I am testing from cygwin, but any *nix shell should be the same

You see this works

$ ./w sed -e "s/cluster_name: 'Test Cluster'/cluster_name: 'Test Clust
er1'/"
argv[0] = F:\blah\w.exe
argv[1] = sed
argv[2] = -e
argv[3] = s/cluster_name: 'Test Cluster'/cluster_name: 'Test Cluster1'/


$

Whereas if you try the one from suspectus

sed -e 's/cluster_name: \'Test Cluster\'/cluster_name: \'Test Cluster1\'/'

You can use the program to find the fault in it

His one doesn't even execute

$ ./w  sed -e 's/cluster_name: \'Test Cluster\'/cluster_name: \'Test C
luster1\'/'
>CTRL-C

Because it has a missing single quote

$ ./w 'fgg
>

among perhaps other problems.

And if you look at suspectus's one, it fails even near the beginning, it breaks on the space

$ ./w  sed -e 's/cluster_name: \'Test Clu
argv[0] = f:\blah\w.exe
argv[1] = sed
argv[2] = -e
argv[3] = s/cluster_name: \Test
argv[4] = Clu

This one works

$ ./w  sed -e 's/cluster_name: '\''Test Cluster'\'\/cluster_name:' '\'
Test' 'Cluster1\'/
argv[0] = F:\blah\w.exe
argv[1] = sed
argv[2] = -e
argv[3] = s/cluster_name: 'Test Cluster'/cluster_name: 'Test Cluster1'/

When you put it together you can try adding a space and a character, and then you see whether your quote mode is on or off. If it's off then if you want to escape a single quote then use \' If it's on then turn it off with ' then do \' If you lose track wther it's on or off then add a space, see if it makes a new parameter or not.

Solution 2:

You would need to escape the single quotes in the sed s command:

sed -e 's/cluster_name: '\''Test Cluster'\''/cluster_name: '\''Test Cluster1'\''/'

Editing single quotes is often tricky. Whereever there is a single quote in the string you replace with '\'' I will try to explain how this works - feel free anyone to improve on this!

'\'' - first quote ends sed string and what follows is parsed by the shell. The backslash renders the character that follows as a simple character (and not a meta-character). The final quote then ends the bash interpreted section and what follows is parsed by sed.