philipovic
philipovic

Reputation: 59

How to use for-loop over csv file to copy files

I have a .csv file where column 8 (named filepath) contains the file location of a file I would like to copy to my home folder in Linux. Now I would like to loop over this column and use the cp function to copy the file to a folder in my home. I tried to do the following:

#!/bin/bash
while read filepath
do
    for filepath in $filepath
        cp $filepath /home/files
    done
done < files.csv

This however does not seem to work. When I replaced the 'cp'in the for loop with an echo statement, it did not print out the file location, but the whole line of the file.

Thank you for your help,

Upvotes: 2

Views: 1920

Answers (2)

anubhava
anubhava

Reputation: 785306

You can read your CSV file line by line into a BASH array and use 8th element from array:

#!/bin/bash

while read -ra cols
do
    cp "${cols[7]}" /home/files
done < files.csv

If csv file is comma delimited then use:

while IFS=, read -ra cols
do
    cp "${cols[7]}" /home/files
done < files.csv

Upvotes: 2

GHugo
GHugo

Reputation: 2654

If it is a csv, then every field is separated by a comma (by default), and you can use cut to select the one you need.

cut -d, -f8 files.csv | xargs -i cp {} /home/files/

Upvotes: 3

Related Questions