how can i optimize the following:
TOTALRESULT="total1=4
total2=9
total3=89
TMEMORY=1999"
TOTAL1=$(echo "${TOTALRESULT}" | egrep "total1=" | awk -F"=" '{print $NF}')
TOTAL2=$(echo "${TOTALRESULT}" | egrep "total2=" | awk -F"=" '{print $NF}')
TOTAL3=$(echo "${TOTALRESULT}" | egrep "total3=" | awk -F"=" '{print $NF}')
TMEMORY=$(echo "${TOTALRESULT}" | egrep "tmemory=" | awk -F"=" '{print $NF}')
i would like to, if possible, avoid the multiple egrep and multiple awk.
rdrtx1
2
typeset -u TOTALRESULT
TOTALRESULT="total1=4
total2=9
total3=89
TMEMORY=1999"
eval "$TOTALRESULT"
1 Like
Note that typeset -u
(values are uppercase) is ksh.
eval can be evil. A bit more careful is
eval $(
echo "$TOTALRESULT" | awk '/^[[:alnum:]_]+=[[:print:]]*$/'
)
1 Like
You could also consider:
#!/bin/ksh
IAm=${##*/}
TmpFile="$IAm".$$
trap 'rm -f "$TmpFile"' EXIT
TOTALRESULT="total1=4
total2=9
total3=89
string=abc=def
TMEMORY=1999"
awk '
BEGIN { FS = OFS = "="
}
{ $1 = toupper($1)
}1' <<EOF > "$TmpFile"
$TOTALRESULT
EOF
. "$TmpFile"
printf '%s is set to %s\n' \
TOTAL1 "$TOTAL1" \
TOTAL2 "$TOTAL2" \
TOTAL3 "$TOTAL3" \
TMEMORY "$TMEMORY" \
STRING "$STRING"
which produces the output:
TOTAL1 is set to 4
TOTAL2 is set to 9
TOTAL3 is set to 89
TMEMORY is set to 1999
STRING is set to abc=def
Although written and tested using a 1993+ version of the Korn shell, this script should work with any POSIX-conforming shell.
RudiC
5
In my bash
4, this seems to work:
. <(echo "${TOTALRESULT^^}")
echo $TOTAL1, $TMEMORY
4, 1999
1 Like