-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFile_Renaming_Current.m
More file actions
101 lines (82 loc) · 2.68 KB
/
File_Renaming_Current.m
File metadata and controls
101 lines (82 loc) · 2.68 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
%% Replace a substring in all files in a directory or all subdirectories
% Created - Alex Salmon - 2019.02.27
% Not yet approved for AOIP use. Last validated: yyyy.mm.dd
%% Imports
addpath('.\lib');
%% Get user input
prompt = {'Desired directory path:',...
'Old string:',...
'New string:',...
'Search subfolders? (y/n)'};
dialog_name = 'Replace a substring in all files';
defaults = {'','','','n'};
opts.Resize = 'on';
%% Loop until input is valid
input_valid = false;
while ~input_valid
answers = inputdlg(prompt, dialog_name, 1, defaults, opts);
if exist('mb', 'var') % Close message box
close(mb);
end
if isempty(answers) % Cancel
return;
end
% Reset error_found
error_found = false;
% Update defaults for quick fixes
defaults = answers;
% unpackaging input data
warning_msg = '';
root_dir = answers{1};
if exist(root_dir, 'dir') == 0
warning_msg = 'Directory not found';
error_found = true;
end
string_to_replace = answers{2};
desired_string = answers{3};
include_subdirs = strtrim(answers{4});
if ~error_found
%% Search for files
search = fullfile(root_dir, sprintf('*%s*', string_to_replace));
if strcmpi(include_subdirs, 'y')
f_list = subdir(search);
% subdir outputs name as the ffname, fix that for the next step
for ii=1:numel(f_list)
[~,name,ext] = fileparts(f_list(ii).name);
f_list(ii).name = [name,ext];
end
elseif strcmpi(include_subdirs, 'n')
f_list = dir(search);
else
warning_msg = 'Input not recognized';
error_found = true;
end
% Check if search comes up empty
if isempty(f_list)
warning_msg = 'No files found with specified substring';
error_found = true;
end
end
%% Validate input
if ~error_found
input_valid = true;
else
mb = msgbox(warning_msg, 'Error', 'Error');
end
end
%% Waitbar
wb = waitbar(0, sprintf('Replacing substring "%s" as "%s"', ...
string_to_replace, desired_string));
wb.Children.Title.Interpreter = 'none';
%% Rename files
for ii=1:numel(f_list)
in_name = f_list(ii).name;
out_name = strrep(in_name, string_to_replace, desired_string);
in_ffname = fullfile(f_list(ii).folder, in_name);
out_ffname = fullfile(f_list(ii).folder, out_name);
% Rename w/ cmd line
eval(sprintf('! ren "%s" "%s"', in_ffname, out_name));
waitbar(ii/numel(f_list), wb)
end
%% Done
close(wb)