Reputation: 47
I have a config file template which I intend to use in the creation of a bash script to automate a installation task, the file has something like this (config.conf
):
...
bootstrap_servers => "HUB_NAMESPACE.servicebus.windows.net:9093"
...
Also I get variables from another file which has something like this (vars.conf
):
...
HUB_NAMESPACE:aNamespace
...
I want to replace HUB_NAMESPACE
in config.conf
. If I make the replacement using the following (there are several HUB_NAMESPACE
to be replaced in the file):
HUB_NAMESPACE=$(awk -F: '/^.*HUB_NAMESPACE/{gsub(/ /,"",$2);print $2}' vars.conf)
sed -i 's^HUB_NAMESPACE^$HUB_NAMESPACE^g' config.conf
The resulting file will be something like this:
...
bootstrap_servers => "aNamespace
.servicebus.windows.net:9093"
...
Which causes the app to crash due to the newline between aNamespace
and .servicebus.windows.net:9093"
.
Is there a way of preventing the insertion of the newline after replacing this way? Is there a better or simpler solution to replace substrings in a file?
Used commands extracted from here:
How get value from text file in linux
How to use sed to find and replace text in files
Also tried:
Remove newline from unix variable
Using sed's append/change/insert without a newline
Upvotes: 0
Views: 264
Reputation:
I tested your command and it worked perfectly without any newline but in sed replace single quotes with double quotes.
HUB_NAMESPACE="$(awk -F: '/^.*HUB_NAMESPACE/{gsub(/ /,"",$2);print $2}' vars.conf)"
sed -i "s^HUB_NAMESPACE^$HUB_NAMESPACE^g" config.conf
Still if you are having problem then try below solution: A simple one liner that uses sed and awk without explicitely defining variable and with in-place file editing
sed -i "s/HUB_NAMESPACE/"$(awk -F: '/^.*HUB_NAMESPACE/{gsub(/ /,"",$2);printf "%s", $2}' vars.conf)"/g" config.conf
Output:
cat config.conf
...
bootstrap_servers => "aNamespace.servicebus.windows.net:9093"
...
The newline insertion is prevented by using printf instead of print
Upvotes: 1