I have a file that I need to look up a value by key using a shell script. The file looks like:
HereIsAKey This is the value
How can I do so
if HereIsAKey
is unique in your file, try this with grep:
myVar=$(grep -Po "(?<=^HereIsAKey ).*" file)
If you only need one variable at a time, you can do something like this:
#!/bin/bash
cat file | while read key value; do
echo $key
echo $value
done
The problem with this solution: The variables are only valid inside the loop. So don't try to do $key=$value
and use it after the loop.
Update: Another way is I/O redirection:
exec 3<file
while read -u3 key value; do
eval "$key='$value'"
done
exec 3<&-
echo "$keyInFile1"
echo "$anotherKey"
If you don't have a grep that supports Perl-compatible regular expressions, the following seems to work:
VAR=$(grep "^$KEY " file | cut -d' ' -f2-)
If the file is unsorted, lookups will be slow:
my_var=$( awk '/^HereIsAKey/ { $1=""; print $0; exit}' value-file )
If the file is sorted, you can get a faster lookup with
my_var=$( look HereIsAkey value-file | cut -d ' ' -f 2- )
get () {
while read -r key value; do
if [ "$key" = "$1" ]; then
echo "$value"
return 0
fi
done
return 1
}
The two return statements aren't strictly necessary, but provide nice exit codes to indicate success or failure at finding the given key. They can also help distinguish between "the key has a empty string for the value" and "the key was not found".
I use a property file that is shared across multiple languages, I use a pair of functions:
load_properties() {
local aline= var= value=
for file in config.properties; do
[ -f $file ] || continue
while read aline; do
aline=${aline//\#*/}
[[ -z $aline ]] && continue
read var value <<<$aline
[[ -z $var ]] && continue
eval __property_$var=\"$value\"
# You can remove the next line if you don't need them exported to subshells
export __property_$var
done <$file
done
}
get_prop() {
local var=$1 key=$2
eval $var=\"\$__property_$key\"
}
load_properties
reads from the config.properties
file populating a set of variables __property_...
for each line in the file, get_prop then allows the setting of a variable based on loaded properties. It works for most of the cases that are needed.
Yes, I do realize there's an eval in there, which makes it unsafe for user input, but it works for what I needed it to do.