jq(或替代方案)将分隔的文件转换为 json 行也前置字段

jq (or alternatives) convert separated file into rows of json also prepending fields

我有一个文件 (file.txt) 如:

field1|field2|field3 
field1|field2|field3 
field1|field2|field3 

(实际上是 83 个字段,20 万行) 我需要将它转换成类似的东西:

field3.field2|{"myname1":"field1","myname2":"field2","myname3":"field3"}
field3.field2|{"myname1":"field1","myname2":"field2","myname3":"field3"}
field3.field2|{"myname1":"field1","myname2":"field2","myname3":"field3"}

我目前分几个步骤进行,但这需要很长时间:

cat file.txt |jq -nR '[inputs | split("|") | {
"myname1": .[0],
"myname2": .[1],
"myname3": .[2]}]' > /var/tmp/tempfile.txt

cat /var/tmp/tempfile.txt | jq -c '.[]' |while read row;do
key=$(echo "$row"|jq -r '(.myname3)+"."+(.myname2)')
echo "$key|$row"
done

是否有更好的方法使用 jq 或其他方法(在 Linux 下)来实现相同的目标?

谢谢

这是一个使用 jq 并使用 tojson 进行字符串插值并转换为 JSON 的解决方案:

jq -Rr './"|" | "\(.[2]).\(.[1])|\({
  "myname1": .[0],
  "myname2": .[1],
  "myname3": .[2]
} | tojson)"' file.txt
field3.field2|{"myname1":"field1","myname2":"field2","myname3":"field3"}
field3.field2|{"myname1":"field1","myname2":"field2","myname3":"field3"}
field3.field2|{"myname1":"field1","myname2":"field2","myname3":"field3"}

Demo