I want to make a copy of a source file in a directory and paste it in the SAME directory but under a different name. I want to loop over a number of participants. The name of the source file varies across participants (though it always has the same onset).
I've written the following loop:
file_root = '/pathtofile/';
sourcefile = 'ABCDE.nii';
destinationfile = 'FGHIJ.nii';
for s = 1:length(subjects) % loops over subjects
copyfile([file_root subjects{s} '/' 'stats' '/' sourcefile], [file_root subjects{s} '/' 'stats' '/' destinationfile]);
end
This loop works fine for the subset of subjects that have the same source file name and it correctly generates the destination file in the SAME directory as the source file.
Now, when I include a wildcard in the source file to deal with varying names in the source files, the loop still works but it generates a new directory called destinationfile which contains a copy of sourcefile (with the same name). So, for example:
file_root = '/pathtofile/';
sourcefile = 'ABCD*.img';
destinationfile = 'FGHIJ.img';
for s = 1:length(subjects) % loops over subjects
copyfile([file_root subjects{s} '/' 'stats' '/' sourcefile], [file_root subjects{s} '/' 'stats' '/' destinationfile]);
end
This loop generates a new directory 'FGHIJ.img' containing the 'ABCDE.img" file within the 'file_root' directory.
So my question is this: how can I use copyfile(source, destination) with a wildcard in the source, which generates a new destination FILE in the same directory.
I hope this makes sense. Any help/suggestions would be greatly appreciated!
When using the Wildcard character, copyfile
assumes you are copying multiple files to a folder, thus interpreting the destination as a directory. You can not use wildcards and set a target file. Use the dir
command to get the matching file name.
I also recommend to use fullfile
to concatenate file path because it is more robust
file_root = '/pathtofile/';
sourcefile = 'ABCD*.img';
destinationfile = 'FGHIJ.img';
for s = 1:length(subjects) % loops over subjects
source_pattern=fullfile(file_root subjects{s} , 'stats' , sourcefile);
matching_files=dir(source_pattern);
source_file=fullfile(file_root subjects{s} , 'stats' , matching_files(1).name);
target_file=fullfile(file_root subjects{s} , 'stats' , destinationfile)
copyfile(source_file, target_file);
end