Copy list of files from a keyword list to another directory

Hello,

I have a folder with a massive amount of files, and I want to copy out a specific subset of the files to a new directory. I would like to use a text file with the filenames listed, but can't get it to work.

The thing I'm hung up on is that the folder names in the path can and do have spaces in them. Thus "2010-36 Olson" gets broken up into "2010-36" and "Olson".

Here is what I have thus far.

#!/bin/bash

kw=$1
dest=$2

while read ifile
	do		
		echo "cp $ifile $dest/$ifile"
	done < $kw
kw=$1 dest=$2

while IFS= read -r ifile; do
  cp -- "$ifile" "$dest/"
done < "$kw"

Worked like a charm. Thank you very much.

Correct me if I am wrong.

IFS= sets the field separator to nothing, ie. spaces won't break the path up into different chunks of data.

read -r causes \ to be read as \ (not as an escape). Will it then be read as a path delimiter like / is?

I don't know what the -- in cp does.

It's slightly different:
IFS= disables unnecessary word/field splitting
and protects you from loosing leading and trailing IFS characters
(an eventual corner case: usually leading or trailing spaces or tabs).
-r prevent the backslash from escaping special sequences,
-- avoids misinterpretation of file names with leading -.

Consider the following:

printf '%s\n' ' a\  ' ' a\  ' 'a\:b' 'a\:b'  | {
  read a 
  IFS= read -r b  
  printf 'a --> |%s|\nb --> |%s|\n' "$a" "$b"
  IFS=: read a b
  printf 'a --> |%s|\nb --> |%s|\n' "$a" "$b"
  IFS=: read -r a b
  printf 'a --> |%s|\nb --> |%s|\n' "$a" "$b"
  } 

It produces:

bash-4.1$ printf '%s\n' ' a\  ' ' a\  ' 'a\:b' 'a\:b'  | {
>   read a 
>   IFS= read -r b  
>   printf 'a --> |%s|\nb --> |%s|\n' "$a" "$b"
>   IFS=: read a b
>   printf 'a --> |%s|\nb --> |%s|\n' "$a" "$b"
>   IFS=: read -r a b
>   printf 'a --> |%s|\nb --> |%s|\n' "$a" "$b"
>   }
a --> |a |
b --> | a\  |
a --> |a:b|
b --> ||
a --> |a\|
b --> |b|

Or:

bash-4.1$ mv -a /tmp/
mv: unknown option -- a
Try `mv --help' for more information.
bash-4.1$ mv -- -a /tmp/
mv: cannot stat `-a': No such file or directory

Many thanks for that detailed explanation.

One question. The code you posted :

kw=$1 dest=$2

while IFS= read -r ifile; do
  cp -- "$ifile" "$dest/"
done < "$kw"

When I run it, it won't copy the last filename in the file. If I add an empty line, it works, but otherwise I end up missing a file.

Any thoughts?

Probably your file is not in proper Unix format in the sense that the last line is missing a linefeed as the last character and then read will not process it.