-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjp_strrepfiles.m
72 lines (49 loc) · 1.58 KB
/
jp_strrepfiles.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
function jp_strrepfiles(baseDir, fileExt, strToFind, strReplacement)
%JP_STRREPFILES Rename files in a directory
if nargin < 4
strReplacement = {};
end
if nargin < 3
strToFind = {};
end
if nargin < 2
fileExt = '';
end
if nargin < 1 || isempty(baseDir)
baseDir = uigetdir;
end
if isempty(fileExt)
files = dir(baseDir);
else
files = dir(fullfile(baseDir, sprintf('*.%s', fileExt)));
end
if ischar(strToFind)
strToFind = {strToFind};
end
if ischar(strReplacement)
strReplacement = {strReplacement};
end
assert(isdir(baseDir), 'Selected directory does not exist.');
assert(length(files)>0, 'Must select at least one file.');
assert(length(strToFind)==length(strReplacement), 'Strings to find, and strings to replace, must be the same length.');
for fileInd = 1:length(files)
% Rename files
thisFile = files(fileInd).name;
if length(thisFile) > 3
[pth, nm, ext] = fileparts(files(fileInd).name);
originalFile = fullfile(baseDir, [nm ext]);
newnm = nm;
for numRep = 1:length(strToFind)
newnm = replace(newnm, strToFind{numRep}, strReplacement{numRep});
end
newFile = fullfile(baseDir, [newnm ext]);
% escape spaces
originalFile = replace(originalFile, ' ', '\ ');
newFile = replace(newFile, ' ', '\ ');
cmd = sprintf('mv %s %s', originalFile, newFile);
[status, ~] = system(cmd);
if status > 0
warning('mv command failed with %s', cmd);
end
end
end