Janus Bahs Jacquet Janus Bahs Jacquet - 4 months ago 17
Bash Question

(OS X Shell) Copying files based on text file containing file names without extensions

Preface: I’m not much of a shell-scripter, in fact not a shell-scripter at all.

I have a folder (

folder/files/
) with many thousand files in it, with varying extensions and random names. None of the file names have spaces in them. There are no subfolders.

I have a plain text file (
filelist.txt
) with a few hundred file names, all of them without extensions. All the file names have corresponding files in
folder/files/
, but with varying extensions. Some may have more than one corresponding file in
folder/files/
with different extensions.

An example from
filelist.txt
:

WP_20160115_15_11_20_Pro
P1192685
100-1373
HPIM2836


These might, for example, correspond to the following files in
folder/files/
:

WP_20160115_15_11_20_Pro.xml
P1192685.jpeg
100-1373.php
100-1373.docx
HPIM2836.avi


(Note the two files named
100-1373
with different extensions.)

I am working on an OS X (10.11) machine. What I need to do is copy all the files in
folder/files/
that match a file name in
filelist.txt
into
folder/copiedfiles/
.1

I’ve been searching and Googling like mad for a bit now, and I’ve found bucketloads of people explaining how to extract file names without extensions, find and copy all files that have no extension, and various tangentially related issues—but I can’t find anything that really helps me figure out how to do this in particular. Doing a
cp ˋcat filelist.txtˋ folder/copiedfiles/
would work (as far as I can tell) if the file names in the text file included extensions; but they don’t, so it doesn’t.

What is the simplest (and preferably fastest) way to do this?



 




1 What I need to do is exactly the same as in this question, but that one is specifically asking about , which is a very different kettle of sea-dwellers.

Answer

This should do it:

while read filename
do
  find /path/to/folder/files/ -maxdepth 1 -type f \
 -name "$filename*" -exec cp {} /path/to/folder/copiedfiles/ \;
done</path/to/filelist.txt
Comments