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
The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.
In Linux/Unix, use set command to change the value of an argument/parameter in a shell script. The arguments we pass to a shell script can be read using the shell variables $1, $2, depends on how many parameters you passed.
To replace a substring with new value in a string in Bash Script, we can use sed command. sed stands for stream editor and can be used for find and replace operation. We can specify to sed command whether to replace the first occurrence or all occurrences of the substring in the string.
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
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" $
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With