问题描述
我修复了需要转换为 JSON 格式的消息文件,如下所示。我如何使用 shell 脚本来转换这些?
来自:
arr.map(val=> val.src.split(",")).flat()
致:
05/03 11:23:19.123456 << 8=FIX.4.2^9=451^35=D^49=abc^56=bcd
05/03 11:23:19.123457 << 8=FIX.4.2^9=451^35=D^49=abc1^56=bcd1
05/03 11:23:19.123458 << 8=FIX.4.2^9=451^35=D^49=abc2^56=bcd2
解决方法
我认为在期望的输出中遗漏 9=451
是一个意外。
$ awk 'BEGIN{FS="\\^|[ <]+"}{printf "{\"time\":\"%s %s\"",$1,$2; for(i=3;i<=NF;i++){split($i,a,/=/);printf ",\"%s\":\"%s\"",a[1],a[2]}; printf "\n"}' fix
{"time":"05/03 11:23:19.123456","8":"FIX.4.2","9":"451","35":"D","49":"abc","56":"bcd"
{"time":"05/03 11:23:19.123457","49":"abc1","56":"bcd1"
{"time":"05/03 11:23:19.123458","49":"abc2","56":"bcd2"
这里有注释来解释它是如何工作的:
# BEGIN rule(s)
BEGIN {
FS = "\\^|[ <]+" # define two field separators,^ and any number or consecutive spaces or left angle brackets
}
# Rule(s)
{
printf "{\"time\":\"%s %s\"",$2 # printing the time (which we treat separately as it's internally "split" by a space.
for (i = 3; i <= NF; i++) { # the other fields we can iterate over,NF in awk is the 'number of fields'
split($i,/=/) # use the loop variable i to reference the fields,split them into an array on the '='
printf ",a[2] # print the array elements formatted,all on one line
}
printf "\n" # add a new line when we're done
}