简体   繁体   中英

Shell script to replace all occurrnces of string with a value

I'm new to shell script. I have a YAML file that consists of placeholder. I need to replace all the occurrences of placeholder <test-name> with a value sweta

script.sh

Name="sweta"

Below is the example of YAML file

metadata:
  name: <test-name>-svc
  namespace: abc
spec:
  selector:
    app: <test-name>
  ports:
  - protocol: TCP
    name: http
    port: 80
    targetPort: 8080

My expected output is:

metadata:
  name: sweta-svc
  namespace: abc
spec:
  selector:
    app: sweta
  ports:
  - protocol: TCP
    name: http
    port: 80
    targetPort: 8080

Can someone help me?

Appreciate all your help. Thanks in advance!

There are two easy ways to accomplish your search and replace <test-name> string with sweta

Note: Assuming your yaml file name is config.yaml


Option-1: Using stream editor command 'sed' as below:

To overwrite the original file

sed -i 's/<test-name>/sweta/g' config.yaml

To write the output to a different file

sed 's/<test-name>/sweta/g' config.yaml > updated_config.yaml

The syntax of sed command is sed -i 's/original/new/g' file.txt

where sed is the command name

-i stands for in-place edit. This option is used to overwrite the original file. If you don't use this, you have to redirect output to a different file as done in second command above.

s stands for substitute

original is the search string

new is the replace string

g is for global (replace all occurrences). Omitting this will just replace only the first occurence

file.txt is the text file (Linux doesn't use extensions like.txt but people often name files with such extensions as a convention to denote file type)


Option-2: Use 'awk' command:

awk is a very powerful text processing command with its own language syntax, but this search and replace is quite easy:

awk '{gsub("<test-name>", "sweta"); print $0}' config.yaml > updated_config.yaml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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