0

I need to edit a files using shell script (sed), I can't seem to get it to work when I use "space" inside my string.

This is the bash script:

##Edit instancegroup files with relevant cluster
CLUSTER_NAME=clusters.dev10.k8s.local
oldcluster="kops.k8s.io/cluster:"
newcluster="kops.k8s.io/cluster: ${CLUSTER_NAME}"
sed -i 's@'${oldcluster}'@'${newcluster}'@g' myfile

This is myfile:

apiVersion: kops/v1alpha2
kind: InstanceGroup
metadata:
  creationTimestamp: 2018-01-03T10:45:43Z
  labels:
    kops.k8s.io/cluster:

And this is the error I get:

administrator@JenkisSrv01:~/awscluster/instancegroup$ ./try.sh
sed: -e expression #1, char 43: unterminated `s' command

When I removing the space from line 4, it is working well:

newcluster="kops.k8s.io/cluster:${CLUSTER_NAME}"

2 Answers 2

3

Unquoted space separates parameters. Quote the variable:

sed -i 's@'"${oldcluster}"'@'"${newcluster}"'@g' myfile

or more readably

sed -i "s@$oldcluster@$newcluster@g" myfile

Note that . has a special meaning in regexes, so kops.k8s.io/cluster: matches e.g. kopsXk8sXio/cluster:. You need to backslash the dots to force the literal meaning.

Sign up to request clarification or add additional context in comments.

Comments

0

add double quotes around variables

sed -i 's@'"${oldcluster}"'@'"${newcluster}"'@g' myfile

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.