user2187367
user2187367

Reputation: 35

How to read properties file in Unix script where key is in another user input variable

I have below property file in same directory.

cancellation.properties

Content:

TestData=My Name

My unix script is abc.sh

Content:

#!/bin/ksh
. ./cancellation.properties

echo  "Please enter data to read"

read data

echo $data

While running I give the value TestData.

I am getting output as "TestData".

But I want output as "My Name". What changes needs to be done here because key will be entered by user.

Upvotes: 1

Views: 888

Answers (4)

Walter A
Walter A

Reputation: 20022

When you don't need to store the variables, and only want to display the value, you can do like this:

read -p "Please enter data to read: " data
grep "^${data}=" ./cancellation.properties | cut -d"=" -f2-

Upvotes: 0

ghoti
ghoti

Reputation: 46856

If there's the possibility that you might want other configuration data read from a file, I'd suggest treating your properties file like a config rather than an embedded script, and putting your data into a structure dedicated to storing configuration. Like an array. Something like this might work:

#!/usr/bin/env bash

declare -A canprop=()

while IFS='=' read -r key value; do
    [[ $key = #* ]] && continue      # handle comments
    canprop[$key]="$value"
done < cancellation.properties

printf '> %s\n' "${canprop[TestData]}"

Note that this particular solution doesn't work if $key is repeated within the configuration file -- the last key read will "win". But it saves you the hassle of putting everything into your "main" namespace.

Upvotes: 0

Cyrus
Cyrus

Reputation: 88776

#!/bin/bash

. <(awk -F '=' '{print $1 "=\""$2"\""}' file)

echo  "Please enter data to read"
read data
echo "${!data}"

Output:

My Name

Upvotes: 2

JNevill
JNevill

Reputation: 50209

You could use awk to get this.

In place of your echo $data put:

awk -F"=" -v data=$data '$1==data{print $2}' cancellation.properties

Which says "Split each record in your cancellation.properties file by an equal sign. If the first field is the value in variable $data (which is the variable data in your awk script set by that -v flag since you can't use shell variables directly in awk) then output the second field.

Also, now that read your question more thoroughly, it looks like you are including your .properties file at the top of the script. This may not be the best answer for you if you wish to proceed. See @cyrus comment to your question where it's noted to quote your variable assignment.

Upvotes: 2

Related Questions