首页 > 解决方案 > Having trouble conditionally moving files based on their names

问题描述

I am trying to write a script that will auto sort files based on the 7th and 8th digit in their name. I get the following error: "Argument must be a string scalar or character vector". Error is coming from line 16:

Argument must be a string scalar or character vector.

Error in sort_files (line 16) movefile (filelist(i), DirOut)

Here's the code:

DirIn = 'C:\Folder\Experiment' %set incoming directory
DirOut = 'C:\Folder\Experiment\1'

eval(['filelist=dir(''' DirIn '/*.wav'')']) %get file list


for i = 1:length(filelist);
    Filename = filelist(i).name
    name = strsplit(Filename, '_');
    newStr = extractBetween(name,7,8);


    if strcmp(newStr,'01')
       movefile (filelist(i), DirOut)
    end

end

Also, I am trying to make the file folder conditional so that if the 10-11 digits are 02 the file goes to DirOut/02 etc.

标签: matlabacoustics

解决方案


First, try avoid using the eval function, it is pretty much dreaded as slow and hard to understand. Specially if you need to create variables. Instead do this:

filelist = dir(fullfile(DirIn,'*.wav'));

Second, the passage:

 name = strsplit(Filename, '_');

Makes name a list, so you can access name{1} or possibly name{2}. Each of these are strings. But name isn't a string, it is a list. extractBetween requires a string as an input. That is why you are getting this problem. But note that you could have simply done:

newStr = name(7:8);

If name was a string, which in Matlab is a char array.

EDIT:

Since it has been now claimed that the error occurs on movefile (filelist(i), DirOut), the likely cause is because filelist(i) is a struct. Wheres a filena name (char array) should have been given at input. The solution should be replacing this line with:

movefile(fullfile(filelist(i).folder, filelist(i).name), DirOut)

Now, if you want to number the output folders too, you can do this: movefile(fullfile(filelist(i).folder, filelist(i).name), [DirOut,filesep,name(7:8)])

This will move a file to /DirOut/01. If you wanted /DirOut/1, you could do this:

movefile(fullfile(filelist(i).folder, filelist(i).name), [DirOut,filesep,int2str(str2num(name(7:8)))])

推荐阅读