2

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,

1
  • What does your input data look like? Can you edit to show us a few lines?
    – Tom Fenech
    May 4, 2015 at 14:44

2 Answers 2

3

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/
2
  • thanks! this worked out fine! I did not think of the cut function
    – philipovic
    May 4, 2015 at 15:05
  • 2
    If you have a version of cp that supports the -t/--target-directory switch, you can do this: cut -d, -f8 files.csv | xargs cp -t /home/files - the advantage of this approach being cp will be invoked the minimum number of times, rather than once per file.
    – Tom Fenech
    May 4, 2015 at 15:21
2

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
1
  • 1
    this also did the job and is a nice alternative of the right answer I chose
    – philipovic
    May 4, 2015 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.