我有这个文件
$img=1.jpg,2.jpg,3.jpg,4.jpg,5.jpg,6.jpg,7.jpg
这是我的代码
# Split on the comma, and create an array
IFS=',' read -ra images <<< "$timg"
# Start the JSON
echo "\"pictures\":["
# loop through the images, and output the JSON
# keep track of the index of output items
counter=1
for image in "${images[@]}"
do
echo -n " {\"source\":\"$image\"}"
# Add a comma unless it is the last element in the array
if [ $counter -lt ${#images[@]} ]
then
echo ","
else
echo ""
fi
(( counter = counter + 1 ))
done
# Close the JSON
echo "]}"
结果是
{"source":"1.jpg"},
{"source":"2.jpg"},
{"source":"3.jpg"},
{"source":"4.jpg"},
{"source":"5.jpg"},
{"source":"6.jpg"},
{"source":"7.jpg"}
我想给comand只读取x个数字并停止。 它可能吗?谢谢 示例我只想运行前5个 结果愿望是:
{"source":"1.jpg"},
{"source":"2.jpg"},
{"source":"3.jpg"},
{"source":"4.jpg"},
{"source":"5.jpg"}
答案 0 :(得分:3)
使用jq
,这几乎是微不足道的:
$ img=1.jpg,2.jpg,3.jpg,4.jpg,5.jpg,6.jpg,7.jpg
$ echo "$img" | jq -R --argjson n 5 'split(",")[:$n] | {pictures: map({source: .})}'
{
"pictures": [
{
"source": "1.jpg"
},
{
"source": "2.jpg"
},
{
"source": "3.jpg"
},
{
"source": "4.jpg"
},
{
"source": "5.jpg"
}
]
}
答案 1 :(得分:2)
答案 2 :(得分:1)
请考虑以下内容:
#!/bin/bash
timg='image1.png,image2.png,image3.png,image4.png,image5.png,image6.png'
# Split on the comma, and create an array
IFS=',' read -ra images <<< "$timg"
# Start the JSON
echo '{ "pictures": ['
for ((i=0; i<5 && i<${#images[@]}; i++)); do
printf ' { "source": "%s" }\n' "${images[i]}"
done | paste -sd ","
echo ']}'
输出:
{ "pictures": [
{ "source": "image1.png" }, { "source": "image2.png" }, { "source": "image3.png" }, { "source": "image4.png" }, { "source": "image5.png" }
]}
注意:
#!/bin/bash
开头,否则可以由POSIX shell运行。echo
上)bash(1)
循环的这种更类似于C的形式,请参见for
。${#images[@]}
得出images
数组中元素的数量。for
数组的末尾或发出了images
对象时,整个5
条件将确保循环终止。考虑将5
设置为变量,以帮助使代码更加自我记录。printf
是一种发出包含双引号但需要注入值的字符串的便捷方法。paste -sd ","
将有效join the lines on its standard input by the provided delimiter。这有助于简化添加逗号的逻辑。