0

I need to search a value inside a file with this format:

key1=value1
key2=value2

Note: the value can have spaces.

I need to obtain the value of the key with a shell script.

I have this code:

myfile="./app.properties"
keyToSearch="EXAMPLE"
value=""
if [ -f "$myfile" ]     
   then
       echo "$myfile found."
       #Search the keyToSearch and obtain the value. 
else
   echo "$myfile not found."
fi

How I can search the key and obtain the value? For example with a while/do or similar.

Thanks!

Javier C.
  • 7,859
  • 5
  • 41
  • 53

1 Answers1

1
VAL=$(grep "$keyToSearch" "$myfile" | cut -d'=' -f2-)

The "-f2-" is basically asking for all the data after the first "=".

Check this: cut(1) - Linux man page

In your case:

myfile="./app.properties"
keyToSearch="EXAMPLE"
value=""
if [ -f "$myfile" ]     
   then
       # echo "$myfile found."   # no noise on success
       #Search the keyToSearch and obtain the value. 
       value="$(grep "$keyToSearch" "$myfile" | cut -d'=' -f2-)"
else
   echo "$myfile not found."
fi
Javier C.
  • 7,859
  • 5
  • 41
  • 53
MostWanted
  • 571
  • 1
  • 5
  • 12