0

I have a column B in my.csv in which each cell references the filename of a document in a directory source_directory/.

I'd like to grab each of those names so I can use them as args for other shell commands (like cp).

Ideally replace list.txt in the following with the contents of column B in my.csv

cp $(<list.txt) target_directory

2 Answers 2

1

How about this:

for i in `awk -F, '{print $2}' my.csv`; do cp "$i" target_directory; done

The awk command is the key; the -F, says to use a comma as a field separator, and then it can print out the second field.

To skip the first line:

for i in `awk -F, 'NR==1{next} {print $2}' my.csv`; do cp "$i" target_directory; done
4
  • Thanks, trying to test this with for i in `awk -F, '{print $2}' my.csv`; do echo $1; done but just getting blank lines as output. Any thoughts what I might be doing wrong?
    – Meltemi
    Oct 22, 2015 at 1:12
  • That should be echo $i not echo $1 at the end; the "for $i" part at the start sets up the shell variable i to be each filename in turn. Oct 22, 2015 at 10:34
  • Might you know how to skip the header row so it's not included? Unfortunately my header row title has 2 spaces in it so it translates to the first 3 lines of $i
    – Meltemi
    Oct 22, 2015 at 19:00
  • Also, running into the issue you mentioned with spaces; need a workaround that works with Macs…
    – Meltemi
    Oct 22, 2015 at 20:25
0

If you know the column number, try:

cut -d, -f2 my.csv | {while read filename; do cp "$filename" target_dir/ ; done}

Assumes you want column #2 and there are no commas in quoted strings that need to ignored.

1
  • There are commas in column 1, which are creating issues with @nickcrabtree's solution.
    – Meltemi
    Oct 22, 2015 at 23:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .