Ivan Santos
Ivan Santos

Reputation: 636

Replace value of a line in a yml with bash

web:
  image: nginx
  volumes:
    - "./app:/src/app"
  ports:
    - "3030:3000"
    - "35729:35729"

I would like to have a bash script to replace the nginx for an argument with bash script.

./script apache

Will replace nginx for apache

Upvotes: 31

Views: 49614

Answers (4)

flowinh2o
flowinh2o

Reputation: 101

You could create your script.sh as follows:

#!/bin/bash
# $1 image value you want to replace
# $2 is the file you want to edit
sed -i "" "/^\([[:space:]]*image: \).*/s//\1$1/" $2

And then run: ./script.sh apache filename.yaml

Upvotes: 10

rmalchow
rmalchow

Reputation: 2769

since this is apparently a docker-compose file, you might want to try

 image: ${webserver_image}

and then set:

 webserver_image=[nginx | apache]

before launching. i believe this should give you a nice interpolation.

Upvotes: 7

Jahid
Jahid

Reputation: 22428

script:

#!/bin/bash
sed -i.bak "s/\bnginx\b/$1/g" file
# \b matches for word boundary
# -i changes the file in-place
# -i.bak produces a backup with .bak extension

Now you can do ./script apache to replace nginx with apache.

Upvotes: 6

riteshtch
riteshtch

Reputation: 8769

You can use this: sed -r 's/^(\s*)(image\s*:\s*nginx\s*$)/\1image: apache/' file

Sample run:

$ cat file
web:
  image: nginx
  volumes:
    - "./app:/src/app"
  ports:
    - "3030:3000"
    - "35729:35729"
$ sed -r 's/^(\s*)(image\s*:\s*nginx\s*$)/\1image: apache/' file
web:
  image: apache
  volumes:
    - "./app:/src/app"
  ports:
    - "3030:3000"
    - "35729:35729"

To persist the changes into the file you can use in-place option like this:

$ sed -ri 's/^(\s*)(image\s*:\s*nginx\s*$)/\1image: apache/' file

If you want it inside a script you can just put the sed command inside a script and execute it with $1 in sustitution.

$ vim script.sh 
$ cat script.sh 
sed -ri 's/^(\s*)(image\s*:\s*nginx\s*$)/\1image: '"$1"'/' file
$ chmod 755 script.sh 
$ cat file 
web:
  image: nginx
  volumes:
    - "./app:/src/app"
  ports:
    - "3030:3000"
    - "35729:35729"
$ ./script.sh apache
$ cat file 
web:
  image: apache
  volumes:
    - "./app:/src/app"
  ports:
    - "3030:3000"
    - "35729:35729"
$

Upvotes: 21

Related Questions