I have a bunch of different kinds of files I need to look at periodically, and what they have in common is that the lines have a bunch of key=value
type strings
Since discussion in commentary has made it clear that a pure-bash solution would also be acceptable:
#!/bin/bash
# ^-- must be /bin/bash, not /bin/sh
#
# ...must also be bash 4.0 or newer.
while read -r -a words; do # iterate over lines of input
declare -A vars=( ) # refresh variables for each line
set -- "${words[@]}" # update positional parameters
for word; do
if [[ $word = *"="* ]]; then # if a word contains an "="...
vars[${word%%=*}]=${word#*=} # ...then set it as an associative-array key
fi
done
echo "${vars[Var]} $5" # Here, we use content read from that line.
done <<<"Version=2 Len=17 Hello Var=Howdy Other"
The <<<"Input Here"
could also be
If you wanted to use $Var
instead of ${vars[Var]}
, then substitute printf -v "${word%%=*}" %s "${word*=}"
in place of vars[${word%%=*}]=${word#*=}
, and remove references to vars
elsewhere. Note that this doesn't allow for a good way to clean up variables between lines of input, as the associative-array approach does.