-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlscell.m
104 lines (87 loc) · 2.71 KB
/
lscell.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
function dirList = lscell(arg, removePathBool, relativePathBool)
%% lscell
% Author: Erik Roberts, 2018
%
% Purpose: returns cell matrix of strings with results from call to dir
%
% Usage: dirList = lscell()
% dirList = lscell(arg)
% dirList = lscell(arg, removePathBool)
% dirList = lscell(arg, removePathBool, relativePathBool)
%
% Inputs (optional):
% arg: argument to dir
% removePathBool: logical whether to remove the path before the files/dirs (default=true)
% relativePathBool: logical whether to convert absolute paths to relative paths (default=false)
% if removePathBool== true, this is ignored.
%
% Output:
% dirList: cellstr list of arg contents from dir. Paths to folders never
% end in trailing filesep, i.e. '/' or '\'.
%
% Tips: in order to search subdirectories, use the '**' glob character in the arg
%
% Note: filters out mac-generated ._* files
%
% See also: DIR
% Dev Note: checked on Mac OS 10.12, Windows 10, Linux Mint with Matlab 2017b
% parse args
if ~nargin || isempty(arg)
arg = '.';
end
if nargin < 2 || isempty(removePathBool)
removePathBool = true; %defaults to true
end
if nargin < 3 || isempty(relativePathBool)
relativePathBool = false; %defaults to false
end
% get dir contents
dirListS = dir(arg);
if isempty(dirListS)
dirList = {};
return
end
% remove first period
if strcmp(dirListS(1).name, '.')
dirListS(1) = [];
end
% remove double period
if strcmp(dirListS(1).name, '..')
dirListS(1) = [];
end
% convert struct to cellstr
dirList = strcat({dirListS.folder}, filesep, {dirListS.name});
% ensure column vector
dirList = dirList(:);
% remove extra cells with '..'
dirList(~cellfun(@isempty, regexp(dirList, '\.\.$'))) = [];
% remove trailing period and filesep from dirs
if isunix || ismac
dirList = regexprep(dirList, '/\.$', '');
else
dirList = regexprep(dirList, '\\\.$', '');
end
% remove duplicated absolute paths from glob
dirList = unique(dirList);
% dirList is cellstr with absolute paths
% remove mac-generated /._* files
dirList = filterMacDotUnderscoreFiles(dirList);
if relativePathBool && ~removePathBool
regexStr = ['^' pwd filesep];
if isunix || ismac
dirList = regexprep(dirList, regexStr, '');
else
regexStr = strrep(regexStr, '\', '\\');
dirList = regexprep(dirList, regexStr, '');
end
end
% dirList is cellstr with absolute paths, or relative paths starting with name
if removePathBool
dirList = cellfun(@removePath, dirList, 'Uni',0);
end
% nested functions
function thisFilename = removePath(thisPath)
[~,name,ext] = fileparts(thisPath);
thisFilename = [name,ext];
end
end