Search code examples
bashawksed

get values of a line, suggestion about performance


I have code in bash scripting to extract some values in variables. Text is:

ct: I al: 3669619 dc: SERVERA mn: CAR or: 19qrh sv: R st: Not_Noticed stt: 2024
0411151219 lu: lt: ms: THAT'S MESAGE run_as: USER sb
: TRADE ap: APPLICATION. jb: JDFSSS ho: HOSTA al: R closed_from_em: nb:
cn: 00000000001

Text is a trap that send to a script, so all the line it pass like argument.

My code is:

line=$(echo $*)
jo=$(echo $* | awk '{print $6":"$9}')
dc=$(echo $* | awk '{print $6}')
aid=$(echo $* | sed 's/.* al:\(.*\) dc.*/\1/' | sed 's/^ //g')
or=$(echo $* | sed 's/.* or:\(.*\) sv.*/\1/' | sed 's/^ //g')
jb=$(echo $* | sed 's/.* jb:\(.*\) ho.*/\1/' | sed 's/^ //g')
ms=$(echo $* | sed 's/.* ms:\(.*\) run_as.*/\1/' | sed 's/^ //g')
callType=$(echo $* | sed 's/ct:\(.*\) al.*/\1/' | sed 's/^ //g')
sv=$(echo $* | sed 's/.* sv:\(.*\) st.*/\1/' | sed 's/^ //g')
st=$(echo $* | sed 's/.* st:\(.*\) stt.*/\1/'|  sed 's/^ //g')
sendTime=$(echo $* | sed 's/.* stt:\(.*\) lu.*/\1/' | sed 's/^ //g')
ru=$(echo $* | sed 's/.* run_as:\(.*\) sb.*/\1/' | sed 's/^ //g')
sb=$(echo $* | sed 's/.* sb:\(.*\) ap.*/\1/' | sed 's/^ //g')
ap=$(echo $* | sed 's/.* ap:\(.*\) jb.*/\1/' | sed 's/^ //g')
ho=$(echo $* | sed 's/.* ho:\(.*\) al.*/\1/' | sed 's/^ //g')
al=$(echo $* | sed 's/.* al:\(.*\) closed_from.*/\1/' | sed 's/^ //g')

Problem is I execute these code a lot of times simultaneously and I need to improve the performance. Do you know how to modify code to improve perfomance? Thanks


Solution

  • Instead of running several commands in a subshell to populate each variable, use Parameter Expansion. It happens in the same shell, which means it's much faster. It's not as powerful as sed or awk, but fortunately, you don't need it here:

    #! /bin/bash
    while read line ; do
        set -- $line
        jo=$6:$9
        dc=$6
        aid=${line#* al: };       aid=${aid% dc:*}
        or=${line#* or: };        or=${or% sv:*}
        jb=${line#* jb: };        jb=${jb% ho:*}
        ms=${line#* ms: };        ms=${ms% run_as*}
        callType=${line#ct: };    callType=${callType%% al:*}
        sv=${line#* sv: };        sv=${sv% st:*}
        st=${line#* st: };        st=${st% stt:*}
        sendTime=${line#* stt: }; sendTime=${sendTime% lu:*}
        ru=${line#* run_as: };    ru=${ru% sb:*}
        sb=${line#* sb: };        sb=${sb% ap:*}
        ap=${line#* ap: };        ap=${ap% jb:*}
        ho=${line#* ho: };        ho=${ho% al:*}
        al=${line##* al: };       al=${al% closed_from*}
    
        echo "JO: $jo."
        echo "DC: $dc."
        echo "AID: $aid."
        echo "OR: $or."
        echo "JB :$jb."
        echo "MS: $ms."
        echo "CALLTYPE: $callType."
        echo "SV: $sv."
        echo "ST: $st."
        echo "SENDTIME: $sendTime."
        echo "RU: $ru."
        echo "SB: $sb."
        echo "AP: $ap."
        echo "HO: $ho."
        echo "AL: $al."
    done