我有一个文件 (silly_log.txt),其中的事件是用数值编码的,我想将这些代码扩展为人类更容易阅读的形式。完成此操作所需的信息位于不同的文件 (dictionary.txt) 中。我的情况看起来像这样:
silly_log.txt(示例):
0
1
5
0
1
7
1
5
0
dictionary.txt(示例):
0:idle
1:receiving data
5:processing data
7:parity error
期望的输出:
0:idle
1:receiving data
5:processing data
0:idle
1:receiving data
7:parity error
1:receiving data
5:processing data
0:idle
谢谢!
最佳答案
用 awk,你可以说:
awk -F':' 'FNR==NR {a[$1]=$2; next} {print $1":"a[$1]}' dictionary.txt silly_log.txt
哪些输出:
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':'
选项将字段分隔符设置为':'
。FNR==NR
当且仅当第一个参数文件dictionary.txt
被读取时匹配,然后它创建一个 map 。{print ..}
片段在读取第二个参数文件时执行,然后根据 map 将代码解释为文本。
编辑
作为替代方案,您也可以只用 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"
关于linux - 根据字典替换事件代码的 Shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53714717/