1

I have a properties file that looks like this:

mysql.username=USERNAME
mysql.pass=PASS

I need to change USERNAME and PASS with variable values passed to shell script. I cannot use sed since that will work fine the first time to replace USERNAME and PASS with "values" but once they are replaced, sed will not find the variable names in the file the second time the script runs and thus an issue.

How can this be handled?

4 Answers 4

1

You can obtain old parameters from the properties file before using sed, e.g.

# get old parameters
$ export oldUsername=$(grep mysql.username $FILE | cut -d'=' -f2)
$ export oldPass=$(grep mysql.pass $FILE | cut -d'=' -f2)

# set new parameters
$ export newUsername=NEW_USERNAME
$ export newPass=NEW_PASS

# change parameters
$ sed -i "s/$oldUsername/$newUsername/g" $FILE
$ sed -i "s/$oldPass/$newPass/g" $FILE
1

You can use below.

[user@xyz ~]$ hh='mysql.username=USERNAME';echo $hh | awk -F"=" '{OFS=FS}{ $2="Mango"; print }'
mysql.username=Mango
1
  • 1
    It would be nice if you could break down each section of the command. This would help people less experienced in bash and possibly help them fix similar problems in the future based on what they learn here.
    – Levi
    Commented Mar 17, 2019 at 2:21
1

You should regenerate this file from a template using your configuration management system of choice.

You could also write a shell script that uses a heredoc to do the same thing. But since we're in DevOps-land you really should be using your configuration management system for these things.

0

Maybe, this is something you can try - in sed they are known as back-references:

$1 - is the value passed for username

$2 - is the value passed for password

\1 captures the back reference within \( and \)

sed -i "s/\(mysql\.username=\).*/\1$1" propertiesfile
sed -i "s/\(mysql\.pass=\).*/\1$2" propertiesfile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.