Wednesday, April 6, 2022

[SOLVED] Bash regex: get value in conf file preceded by string with dot

Issue

I have to get my db credentials from this configuration file:

# Database settings

Aisse.LocalHost=localhost
Aisse.LocalDataBase=mydb
Aisse.LocalPort=5432
Aisse.LocalUser=myuser
Aisse.LocalPasswd=mypwd

# My other app settings

Aisse.NumDir=../../data/Num
Aisse.NumMobil=3000

# Log settings
#Aisse.Trace_AppliTpv=blabla1.tra
#Aisse.Trace_AppliCmp=blabla2.tra
#Aisse.Trace_AppliClt=blabla3.tra
#Aisse.Trace_LocalDataBase=blabla4.tra

In particular, I want to get the value mydb from line

Aisse.LocalDataBase=mydb

So far, I have developed this

mydbname=$(echo "$my_conf_file.conf" | grep "LocalDataBase=" | sed "s/LocalDataBase=//g" )

that returns

mydb #Aisse.Trace_blabla4.tra

that would be ok if it did not return also the comment string.

Then I have also tryed

mydbname=$(echo "$my_conf_file.conf" | grep "Aisse.LocalDataBase=" | sed "s/LocalDataBase=//g" )

that retruns void string.

How can I get only the value that is preceded by the string "Aisse.LocalDataBase=" ?


Solution

I'm afraid you're being incomplete:
You mention you want the line, containing "LocalDataBase", but you don't want the line in comment, let's start with that:

A line which contains "LocalDataBase":

grep "LocalDataBase" conf.conf.txt

A line which contains "LocalDataBase" but who does not start with a hash:

grep "LocalDataBase" conf.conf.txt | grep -v "^ *#"

??? grep -v "^ *#"

That means: don't show (-v) the lines, containing:

  • ^ : the start of the line
  • * : a possible list of space characters
  • # : a hash character

Once you have your line, you need to work with it:
You only need the part behind the equality sign, so let's use that sign as a delimiter and show the second column:

cut -d '=' -f 2

All together:

grep "LocalDataBase" conf.conf.txt | grep -v "^ *#" | cut -d '=' -f 2

Are we there yet?
No, because it's possible that somebody has put some comment behind your entry, something like:

LocalDataBase=mydb #some information

In order to prevent that, you need to cut that comment too, which you can do in a similar way as before: this time you use the hash character as a delimiter and you show the first column:

grep "LocalDataBase" conf.conf.txt | grep -v "^ *#" | cut -d '=' -f 2 | cut -d '#' -f 1

Have fun.



Answered By - Dominique
Answer Checked By - David Marino (WPSolving Volunteer)