Rajesh
Rajesh

Reputation: 199

Update a line in config file from bash script using sed / awk or other tool

I have to update a specific line in a configuration file. The line I need to update is below. I want to update the field SERVICE_NAME=OriginalValue with SERVICE_NAME=NewVaule. Unfortunately, the 'OriginalValue' is not a fixed string. It consists of alphabetic characters (upper and lower), numbers and periods.

Also, the SERVICE_NAME is on several lines and I only want to update the line that has jdbc_url in it.

The item I tried is below, but I need to only replace up to the first parenthesis.

sed -i '/s_apps_jdbc_connect_descriptor/s/SERVICE_NAME.*)/SERVICE_NAME=NewValue/' work.xml

I'm not sure how to proceed. The only requirement is that the command is executable from bash and uses tools that are in a reasonable Linux distro.

<jdbc_url oa_var="s_apps_jdbc_connect_descriptor">jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=YES)(FAILOVER=YES)(ADDRESS=(PROTOCOL=tcp)(HOST=myhostname.com)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=OriginalValue)))</jdbc_url>

Upvotes: -1

Views: 745

Answers (2)

sjsam
sjsam

Reputation: 21965

If you're looking for a script this, say config_editor would do :

#!/bin/bash
# $1 - new value $2 - /path/to/config_file
if [ ! "$#" -eq 2 ]
then
  echo "Usage : ./config_editor new_value /path/to/config_file"
  exit 1
elif [ ! -e "$2" ]
then
  echo "Config file doesn't exist, please check the path"
  exit 1
fi
sed -Ei.bak '/^<jdbc_url/{s/(SERVICE_NAME=)[^)]*\)/\1'"$1"'\)/}' "$2"
# -E enables extended regex for sed, a bit more portable than -r
# -i enables inplace edit but do keep a backup of the original file
# .bak with -i appends a suffix .back to the backup file

Run it as

./config_editor new_value /path/to/config_file

Upvotes: 2

Barmar
Barmar

Reputation: 781004

To perform a substitution only on lines that match a pattern, use the pattern as the address expression for the substitution command.

sed '/jdbc_url/s/SERVICE_NAME=OriginalValue/SERVICE_NAME=NewVaule/' filename

Upvotes: 1

Related Questions