简体   繁体   English

bash使用sed从变量添加字符串

[英]bash add string from variable using sed

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. 我需要使用shell脚本(sed)编辑文件,当我在字符串中使用“空格”时,似乎无法使其正常工作。

This is the bash script: 这是bash脚本:

##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 : 这是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: 当我从第4行删除空间时,它运行良好:

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

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 eg kopsXk8sXio/cluster: . 在正则表达式中有特殊含义,因此kops.k8s.io/cluster:匹配例如kopsXk8sXio/cluster: You need to backslash the dots to force the literal meaning. 您需要反斜杠点以强制字面含义。

在变量周围添加双引号

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM