Search code examples
linuxshellsedgrepcut

Shell command that replaces event codes according to a dictionary


I've got a file (silly_log.txt) in which events are encoded with numeric values and I'd like to expand these codes to a form that can be read by humans more easily. The information that is required to accomplish this is in a different file (dictionary.txt). My situation looks something like this:

silly_log.txt (example):

0
1
5
0
1
7
1
5
0

dictionary.txt (example):

0:idle
1:receiving data
5:processing data
7:parity error

desired output:

0:idle
1:receiving data
5:processing data
0:idle
1:receiving data
7:parity error
1:receiving data
5:processing data
0:idle

Thanks!


Solution

  • With awk, you can say:

    awk -F':' 'FNR==NR {a[$1]=$2; next} {print $1":"a[$1]}' dictionary.txt silly_log.txt
    

    which outputs:

    0:idle
    1:receiving data
    5:processing data
    0:idle
    1:receiving data
    7:parity error
    1:receiving data
    5:processing data
    0:idle
    
    • -F':' option sets the field separator to ':'.
    • FNR==NR matches if and only if the first argument file dictionary.txt is read, then it creates a map.
    • The {print ..} fragment is executed while the second argument file is read, then it interprets the codes to the texts based on the map.

    EDIT
    As an alternative, you can also say just with bash:

    declare -a a
    
    while IFS=: read -r code str; do
        a["$code"]="$str"
    done < "dictionary.txt"
    
    while read -r code; do
        printf "%d:%s\n" "$code" "${a[$code]}"
    done < "silly_log.txt"