将CSV中的URL下载到第一个字段中给出的子目录中

问题描述 投票:-1回答:2

所以我想将我的产品导出到我的新网站。我有一个包含这些数据的csv文件:

product id,image1,image2,image3,image4,image5
1,https://img.url/img1-1.png,https://img.url/img1-2.png,https://img.url/img1-3.png,https://img.url/img1-4.png,https://img.url/img1-5.png
2,https://img.url/img2-1.png,https://img.url/img2-2.png,https://img.url/img2-3.png,https://img.url/img2-4.png,https://img.url/img2-5.png

我想做的是制作一个脚本来读取该文件,使用产品ID命名目录,下载产品图像并将它们放在自己的文件夹中(文件夹1 => image1-image5 of product id 1,folder 2 =>产品ID 2的image1-image5,依此类推)。

如果更容易,我可以制作普通的文本文件,而不是使用excel格式。谢谢你。

对不起,我真的很新。我还没有完成代码,因为我很无能,但我想做的是这样的:

for id in $product_id; do
  mkdir $id && cd $id && curl -o $img1 $img2 $img3 $img4 $img5 && cd ..
done
bash shell csv
2个回答
-1
投票

如果你按照@Aaron给你的好建议,这段代码可以帮助你,因为你似乎是bash的新手,我注释了代码以便更好地理解。

#!/bin/bash

# your csv file
myFile=products.csv

# number of lines of file
nLines=$(wc -l $myFile | awk '{print $1}')

echo "Total Lines=$nLines"

# loop over the lines of file
for i in `seq 1 $nLines`;
    do
        # first column value
        id=$(sed -n $(($i+1))p $myFile | awk -F ";" '{print $1}')

        line=$(sed -n $(($i+1))p $myFile)

        #create the folder if not exist
        mkdir $id 2>/dev/null

        # number of images in the line
        nImgs=$(($(echo $line | awk -F ";" '{print NF-1}')-1))

        # go to id folder
        cd $id
        #loop inside the line values
        for j in `seq 2 $nImgs`;
            do
                # getting the image url to download it
                img=$(echo $line | cut -d ";" -f $j)
                echo "Downloading image $img**";echo
                # downloading the image
                wget $img
        done 
        # go back path
        cd ..
done

0
投票

这是一个快速而肮脏的尝试,希望至少可以让你知道如何处理这个问题。

#!/bin/bash

tr ',' ' ' <products.csv |
while read -r prod urls; do
     mkdir -p "$prod"
     # Potential bug: urls mustn't contain shell metacharacters
     for url in $urls; do
         wget -P "$prod" "$url"
     done
done

如果你喜欢( cd "$prod" && curl -O "$url" ),你可以等同地做curl;我通常这样做,虽然使用wget设置输出目录的选项的可用性是方便的。

如果您的CSV在字段周围包含引号,或者您需要处理包含shell元字符的URL(不规则空格,恰好与当前目录中的文件匹配的通配符等;但最突出的是&,这意味着在后台运行shell命令)也许尝试类似的东西

while IFS=, read -r prod url1 url2 url3 url4 url5; do
    mkdir -p "$prod"
    wget -P "$prod" "$url1"
    wget -P "$prod" "$url2"
    : etc
done <products.csv

其中(模数固定引用)非常接近您的尝试。

或者可能切换到较不古怪的输入格式,也许可以从CSV中随时生成

awk -F , 'function trim (value) {
       # Trim leading and trailing double quotes
       sub(/^"/, "", value); sub(/"$/, "", value);
       return value; }
  { prod=trim($1);
    for(i=2; i<=NF; ++i) {
        # print space-separated prod, url
        print prod, trim($i) } }' products.csv |
while read -r prod url; do
    mkdir -p "$prod"
    wget -P "$prod" "$url"
done

它将CSV拆分为具有相同产品ID和每个URL的重复行,并删除任何CSV引用,然后将其循环覆盖。带有mkdir选项的-p并不介意目录是否已存在。

© www.soinside.com 2019 - 2024. All rights reserved.