Issue
I have two different configuration files like following :
# Database
database.url=jdbc:mysql://127.0.0.1/database_name
and
# API
api.port=5005
I would like to change both of them, by utilizing sed commands in a shell script.
What I have done & Problem :
This is the shell script that I made to accomplish it :
DB_CONFIG_FILE=~/configs/database.properties
MYSQL_CONTAINER_PORT=3113
sed -i 's~^database.url=jdbc:mysql://127.0.0.1/database_name.*database.url=jdbc:mysql://127.0.0.1:${MYSQL_CONTAINER_PORT}/database_name~' $DB_CONFIG_FILE
TM_CONFIG_FILE=~/configs/tm.properties
PORT=5100
sed -i 's~^api.port=5005.*api.port=${PORT}~' $TM_CONFIG_FILE
However, that gave me an error saying :
sed: -e expression #1, char : unterminated `s' command
Is there a workaround to include those variables declared in the script? Thank you
Expectation :
My expectation is to modify the configuration files to something like this :
# Database
database.url=jdbc:mysql://127.0.0.1:3113/database_name
and
# API
api.port=5100
Solution
Few reasons:
- Your sed command is broken as there is no substitution after delimiter
~
- Shell variables won't expand in single quotes, use double quotes
- RegEx meta characters such
.
,*
.?
,+
need to be escaped in sed regex.
Following sed should work for you:
dbCfgFile=~/configs/database.properties
mysqlContainerPort=3113
sed -E -i.bak "s~^(database\.url=jdbc:mysql://127\.0\.0\.1)(/.*)~\1:$mysqlContainerPort\2~" "$dbCfgFile"
Note that I am suggesting a regex with .
escaped and using capture groups and back-references to avoid repeating same text in pattern and substitution.
Similarly for second sed
use:
tmCfgFile=~/configs/tm.properties
port=5100
sed -E -i.bak "s/^(api\.port=).*/\1${port}/" "$tmCfgFile"
PS: I have renamed your shell variables from all caps to camel case to avoid clash with shell env variables.
Answered By - anubhava Answer Checked By - Pedro (WPSolving Volunteer)