Sed command with apostrophe

sed

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

I have this error message:

  sed: -e expression, char 20: unterminated `s' command

Please, how can i correct the sed command ?

Best Answer

$ 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.

Related Question