gpt4 book ai didi

linux - 如何使用 shell 脚本将文本文件转换为 JSON 文件

转载 作者:行者123 更新时间:2023-12-02 18:04:40 25 4
gpt4 key购买 nike

我有一个看起来像这样的文件 (myfile.txt)

GYFUFGYO1  KMP-app   james@qt.com  CODE_SMELL
GYFUFGYO2 KMP-app james@qt.com CODE_SMELL
GYFUFGYG3 AFP-Login nathan@qt.com BUG
GYFUFGYG4 AFP-Login nathan@qt.com BUG
GYFUFGYO5 KMP-app james@qt.com CODE_SMELL
GYFUFGYO6 KMP-app james@qt.com CODE_SMELL

我必须将此文本内容写入 JSON 文件 (myfile.json)。这是预期的输出

[
{"ApplicationName":"KMP-app","BuildBreakReason":"CODE_SMELL","DefectAuthor": "james@qt.com"},
{"ApplicationName":"KMP-app","BuildBreakReason":"CODE_SMELL","DefectAuthor": "james@qt.com"},
{"ApplicationName":"AFP-Login","BuildBreakReason":"BUG","DefectAuthor": "nathan@qt.com"},
{"ApplicationName":"AFP-Login","BuildBreakReason":"BUG","DefectAuthor": "nathan@qt.com"},
{"ApplicationName":"KMP-app","BuildBreakReason":"CODE_SMELL","DefectAuthor": "james@qt.com"},
{"ApplicationName":"KMP-app","BuildBreakReason":"CODE_SMELL","DefectAuthor": "james@qt.com"}
]

这是我尝试过的

我创建了一个名为“textconvert.sh”的文件。然后写了一个这样的shell脚本。

echo"[" >> myfile.json
echo {"ApplicationName":"KMP-app","BuildBreakReason":"CODE_SMELL","DefectAuthor": "james@qt.com"}, >> myfile.json
echo {"ApplicationName":"KMP-app","BuildBreakReason":"CODE_SMELL","DefectAuthor": "james@qt.com"}, >> myfile.json
echo {"ApplicationName":"AFP-Login","BuildBreakReason":"BUG","DefectAuthor": "nathan@qt.com"}, >> myfile.json
echo {"ApplicationName":"AFP-Login","BuildBreakReason":"BUG","DefectAuthor": "nathan@qt.com"}, >> myfile.json
echo {"ApplicationName":"KMP-app","BuildBreakReason":"CODE_SMELL","DefectAuthor": "james@qt.com"}, >> myfile.json
echo {"ApplicationName":"KMP-app","BuildBreakReason":"CODE_SMELL","DefectAuthor": "james@qt.com"} >> myfile.json
echo"]" >> myfile.json

但我不允许这样硬编码。我现在想的是,

写一个循环扫描“myfile.txt”然后将列值分配给变量。然后写一个json文件。

谁能帮我解决这个问题?

最佳答案

使用任何 awk:

$ cat tst.awk
BEGIN {
fmt = "%s{\"ApplicationName\":\"%s\",\"BuildBreakReason\":\"%s\",\"DefectAuthor\": \"%s\"}"
print "["
}
{ printf fmt, sep, $2, $4, $3; sep="," ORS }
END { print ORS "]" }

$ awk -f tst.awk myfile.txt
[
{"ApplicationName":"KMP-app","BuildBreakReason":"CODE_SMELL","DefectAuthor": "james@qt.com"},
{"ApplicationName":"KMP-app","BuildBreakReason":"CODE_SMELL","DefectAuthor": "james@qt.com"},
{"ApplicationName":"AFP-Login","BuildBreakReason":"BUG","DefectAuthor": "nathan@qt.com"},
{"ApplicationName":"AFP-Login","BuildBreakReason":"BUG","DefectAuthor": "nathan@qt.com"},
{"ApplicationName":"KMP-app","BuildBreakReason":"CODE_SMELL","DefectAuthor": "james@qt.com"},
{"ApplicationName":"KMP-app","BuildBreakReason":"CODE_SMELL","DefectAuthor": "james@qt.com"}
]

关于 我现在想的是,写一个循环来扫描“myfile.txt”... 从你的问题 - 不,不要那样做。参见 why-is-using-a-shell-loop-to-process-text-considered-bad-practice .

关于linux - 如何使用 shell 脚本将文本文件转换为 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73568203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com