0

I want to be able to modify db001 with a string I pass into the command via CLI. At any given time db001 could be a different value so I can't just look for that value.

./myscript modify_db <new value>

myfile.txt

./myscript modify_db mynewdbname002
Before: database_node=db001.mydomain.local
After: database_node=mynewdbname002.mydomain.local    

./myscript modify_db db003
Before: database_node=mynewdbname002.mydomain.local
After: database_node=db003.mydomain.local    
2
  • 1
    So the second call is supposed to look for the replacement string from the previous call? Commented Jan 13, 2017 at 16:46
  • correct. i dont care what the previous call was. maybe someone edits the file manually after the fact. Commented Jan 13, 2017 at 16:49

3 Answers 3

1

You can use this sed command inside your script:

sed "s/^\(database_node=\)[^.]*/\1$1/" file

Example:

s='database_node=db001.mydomain.local'

repl() {
   sed "s/^\(database_node=\)[^.]*/\1$1/" <<< "$s";
}

and call it as:

repl mynewdbname002
database_node=mynewdbname002.mydomain.local

repl db003
database_node=db003.mydomain.local
Sign up to request clarification or add additional context in comments.

Comments

1

You could have a script like, just like below taking an input argument having the replacement value,

#!/bin/bash
perl -lpe "s/database_node=(\w+)/database_node=$1/g" file

and just do

./script.sh newdbname

Use the -i flag for in-place replacement and -i.bak for in-place replacement with a backup of your original file

perl -lpe -i.bak "s/database_node=(\w+)/database_node=$1/g" file

(or) with a simple bash function

function replaceFile() {
    perl -lpe -i.bak "s/database_node=(\w+)/database_node=$1/g" file
}

Comments

0

I would avoid trying to produce the new state from the previous state and rather just use a template :

function modify_db() { 
    echo "database_node=$1.mydomain.local"
}

I use echo here for illustration but you should obviously do whatever you want to do with the "database_node=$1.mydomain.local".

Supposing it should modify the only line starting with database_node from a file db_conf after having printed the old value :

function modify_db() {
    echo "Before: $(grep '^database_node=' db_conf)"
    sed -i "s/^database_node=.*\.mydomain\.local/database_node=$1.mydomain.local/" db_conf
    echo "After: $(grep '^database_node=' db_conf)"
}

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.