下面是一个 for 循环的片段,我在其中对 txt 文件名进行排序。然后我尝试将结果保存在 json 格式文件中。但是,由于最后一个原因,它会导致无效的 json 格式,
插入obj
。我如何将 for 循环中的值转换为 json 格式?
script
dir = "myfiles/test/"
echo "[" >> test.json
for dir in "${array[@]}"; do
#reverse the result of comparisons
file=$(find "$dir" -maxdepth 1 -type f -iname '*.txt' | awk "NR==$i")
[[ -n $file ]] && echo "{ \"filepath\" : \"$file\" }," >> test.json
done
echo "]" >> test.json
所需输出
[
{ "filepath" : "myfiles/test/sdfsd.txt" },
{ "filepath" : "myfiles/test/piids.txt" },
{ "filepath" : "myfiles/test/saaad.txt" },
{ "filepath" : "myfiles/test/smmnu.txt" }
]
电流输出
[
{ "filepath" : "myfiles/test/sdfsd.txt" },
{ "filepath" : "myfiles/test/piids.txt" },
{ "filepath" : "myfiles/test/saaad.txt" },
{ "filepath" : "myfiles/test/smmnu.txt" },
]
请注意,除第一行之外的每一行均以“,\n”开头。
dir="myfiles/test/"
prefix=""
echo "[" >> test.json
for dir in "${array[@]}"; do
#reverse the result of comparisons
file=$(find "$dir" -maxdepth 1 -type f -iname '*.txt' | awk "NR==$i")
[[ -n $file ]] &&
printf '%b{ "filepath": "%s" }' $prefix "$file" >> test.json
prefix=",\n"
done
echo
echo "]" >> test.json
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)