Exclude System or Hidden Folders from Mac Dir List

조회 수: 42 (최근 30일)
Matt O'Brien
Matt O'Brien 2023년 4월 21일
답변: Matt O'Brien 2023년 5월 9일
Here is the attributes for the System Volume Information directory on a Mac disk.
How can I get a Dir listing of all folders on a Mac drive but exclude hidden or system folders.
Note (see 2) ... System Attribute for a System file is Nan... So, if I cannot use the attribute function how can I establish (reliably) what are system or hidden files.
AVF_INFO and 'System...' are hidden directories . DCIM and PRIVATE are 'normal' dirs I expect to find in a dir list.
Note 2. I have already eliminated lots of directories which I also needed to exclude from my Dir list.
MyDirList = HD_FullList([HD_FullList.isdir]); %remove files from list
MyDirList=MyDirList(~ismember({MyDirList.name},{'.','..'}));% remove . & ..
MyDirList=MyDirList(~ismember({MyDirList.name},{'$RECYCLE.BIN'}));% remove recycle bin
MyDirList=MyDirList(~ismember({MyDirList.name},{'.Trashes'}));% remove trash dirs
MyDirList( startsWith({MyDirList.name}, '.') ) = []; %exclude hidden files ie starting with .
And excuse me for venting a little rant here.... Why is it so ridulously difficult to get dir lists of files and directories on Mac and Win. This is excruciatingly painful... and seriously error prone. This might be my last MatLab project.
  댓글 수: 25
Matt O'Brien
Matt O'Brien 2023년 4월 25일
편집: Matt O'Brien 2023년 4월 25일
Can some one show me how to execute the following 'ls' commands from inside MatLab, along the following lines.
MyLsList = ls -a MyDirString
MyLsList = ls MyDirString
so I can capture the related ls output in the variable MyLsList and MyDirString contains the target directory of my choice.
I can get the Ls command to work but unable to add in the -a parameter. If I can get these two Ls commands to work, one should contain all all entries incl hidden and the second may be the list I am looking for.
Or perhaps I need to recognise the difference between these lists to find the hidden entries.
This would be a possible workaround for me.
dpb
dpb 2023년 4월 25일
편집: dpb 2023년 4월 25일
I don't have a non-Windoes OS to illustrate with, but the format should suffice to see syntax.
>> [~,s]=system('dir /a:h /b c:\*.sys')
s =
'hiberfil.sys
pagefile.sys
swapfile.sys
'
>>
For a variable string use something like (be sure to be careful to keep embedded spaces where needed between command switches and the filename, etc., ...). For example,
cmd=strcat('dir /a:h /b ',fn);
looks just right, doesn't it? But, it has the nasty behavior that it does an internal strtrim() on the arguments before doing the catenation so you end up with the filename string being directly appended to the last command switch and Boom! the call fails and you'll spend a long time looking to figure out why... :( To make the behavior even more obtuse, if you use a cellstr or string class, then it doesn't trim--go figure.
>> fn=fullfile('c:','*.sys');
>> cmd=['dir /a:h /b ' fn];
>> [~,s]=system(cmd)
s =
'hiberfil.sys
pagefile.sys
swapfile.sys
'
>>
NOTA BENE: the above is one string with embedded \n -- remember the caveat that hopefully nobody was nasty enough to have used one in an actual filename on your system...that's a nasty.
>> split(s,newline)
ans =
4×1 cell array
{'hiberfil.sys'}
{'pagefile.sys'}
{'swapfile.sys'}
{0×0 char }
>>
That's with MS CMD processor that MATLAB uses "out-of-the-box" -- another aberration is that TMW ignores the COMSPEC environment variable so one has to go thru gyrations to get another shell. I use the JPSoft (shameless plug for super product; not related, just 20+ year user) replacement which has more functionality included a "/f" switch besides "/b" to remove the header/trailer info; it returns the fully-qualified name for all.
@Walter Roberson is bound to come along before long and can/will give a specific example, undoubtedly! :)

댓글을 달려면 로그인하십시오.

답변 (5개)

Matt O'Brien
Matt O'Brien 2023년 4월 25일
Thanks for the syntax.
I got the following to work ... in principle ...
-a includes hiddenitems
-R recursive mode ...
clc
MyLsString= strcat('ls -a -R /Volumes/MoB_WD_5TB/DeeAprilTravel2023');
[~,s]=system(MyLsString);
MyList = splitlines(s);
MyLen = length(MyList);
z=0;
But I am not sure I have the skills or trust my efforts to untangle the output.
Splitlines.
I used split lines to get lines raather than a single long text string. This seems to work ... but not sure I can trust the output....
More troubling....
Data Returned.
No doubt this data can be unscrambled... but I would not trust myself to do this.
Also ... I see lots of funny scenarios.
eg. Line 7 DCIM is a very important sub directory ... but it is on the same line as 'fseventsd-uuid'
Maybe this is a splitline issue.
So ... my summary ... Good to know how to issue system commands from Matlab .... but looks scary to try and convert this into useful data to resolve my issue.
  댓글 수: 4
Matt O'Brien
Matt O'Brien 2023년 4월 25일
All good info.
I also take your point re use of -a.... my intention was to create 2 lists (include exclude hidden ) and compare the difference, but got sidelined with the splitline issue.
I spotted the -1 option, but did not grasp its use.
I will play around further with ls tomorrow, more to understand it further than to expect to find a solution.
Matt O'Brien
Matt O'Brien 2023년 4월 26일
All good points... good tip re 'length' .... use of strcat was to allow me play with different combinations of parameters... in this case no parameters ... so looked superfluous....
Here is a screen grab of result of -1Ra ... have not figured out yet how to to try and structure the output...
This is the result of just hovering over the s value....
I am going to take a rest on this for a while... I am not going to try and convert the text into a structured dataset.... I can see some clues how to do that ... but not keen to follow that path...
I will keep you posted on any developments...
I sent you a PM ... just fyi...
Regards...
Matt O'Brien

댓글을 달려면 로그인하십시오.


Matt O'Brien
Matt O'Brien 2023년 5월 8일
Update. Explore finding Hidden and Visible files/folders using Apple native tools.
I have spent considerable time exploring the Apple native apps such as Swift/Xcode and AppleScript.
My objective is two fold.
  1. Explore, using native Apple apps, if I can separate visible and hidden dirs using a script or app
  2. Recce the possibility of aborting MatLab and reverting to Swift/Xcode and build my apps on Mac / Ipad /Iphone.
I built the very basic and crude Apple script below.... It opens a folder selection dialog, where I select an SD card in a connected card reader.
It has 2 basic loops, both just at the top folder level (ie non recursive). The first looks for hidden folders and the second loop looks for visible folders. In each case it lists (logs) the folders found. The output is extremely crude... will make it pretty later.
Here is the results. It is a screen grab from the AppleScript IDE. Clearly, I can select and identify hidden folders and/or visible folders.
My Key Point.
I had to learn Apple developing and scripting tools from scratch. If I can do this .... then it must be seriously possible for MatLab to add a feature to the current Dir function or create a new function (to preserve compatibility / avoid bugs) which will enable the basic ability to be able to list visible / hidden files/folders with simplefunction option.
I am horrified that such an important feature in such an important function is missing and that I have to go to this level of effort to resolve in a reliable way.
In AppleScript I can identify visible / hidden folders with a single clear statement.
"set MyList to folders of the_folder whose visible is false"
I am enclosing the script I used (it is crude) just for your info.
My Next Action.
I plan to refine this script in due course, get it working for all subfolders.... and then begin to migrate my field apps from MaLab to work on native Apple code. A winter project. This will allow me to use my MacAir very efficiently in the field for ingesting high volume media files and manage the digital assets accumulated. I may even be able to get my app to work on iPhone or iPads, especially with USB C iPhones in the pipeline. That is all nice to have. What is critical for me now is I have a solution which is fit for purpose and not dependent on hard coding to cater for the infinite variety of hidden files or folders stored by different camera companies when saving images / video to digital media.
I will leave this post here for a week or so. If no other solution found by then I plan to mark this post as the answer to my query.
-- Get all files in a selected folder
-- Explore visible / hidden folders
log "Hidden"
-- Get user folder
set the_path to choose folder with prompt "Choose your folder..."
my file_to_folder(the_path)
on file_to_folder(the_folder)
tell application "System Events"
-- Get all folders = hidden
set MyList to folders of the_folder whose visible is false
repeat with MyItem in MyList
-- Remove extension of the file name
set the_file_ext to name extension of MyItem
set the_name to name of MyItem as string
log the_name
end repeat
end tell
log " "
log "Visible"
tell application "System Events"
-- Get all folders = visible
set MyList to folders of the_folder whose visible is true
repeat with MyItem in MyList
-- Remove extension of the file name
set the_file_ext to name extension of MyItem
set the_name to name of MyItem as string
log the_name
end repeat
end tell
end file_to_folder
-- Ending dialog
display dialog ("It's done!") buttons {"Perfect!"}
  댓글 수: 8
dpb
dpb 2023년 5월 8일
I still agree with the initial point that TMW should have either incorporated the common OS switches in the existing dir() function LONG ere now (like in the beginning) or have produced alternate functionality. It is, after all, the user-friendly rapid-development environment that is what it's all about; leaving this to the user to deal with is, simply put, "just plain rude!" as one of my granddaughters is wont to opine...it's doable, yes, but why can't we simply just use "/h" or "/-h" in some form other than calling the OS and parsing it ourselves?
Back years ago, I had done for Windows; unfortunately, it was another of the utilities that got left on the corporate machine when retired to the farm and forgot to offload that stuff before leaving...what I really miss is the mex extension that took a Fortran FORMAT string and variables then passed on the the Fortran i/o library --a MUCH nicer solution than writing those ugly C formatting strings with no repeat counts, etc., ...without paying consulting client, it hasn't been enough of an issue to have bothered to regenerate although at the moment I can't even get a Fortran compiler to link mex; not having the "high-priced spread" of the Intel compiler. Since they support gcc, there's no reason the Fortran compiler shouldn't be supported as well, but I've been unable to solve the name-mangling issues to link. Anyways, sorry for the side rant; we old fogeys tend to wander off...
Matt O'Brien
Matt O'Brien 2023년 5월 8일
Aside. I cut my teeth using Fortran. There is a gas pipeline in Ireland whose concrete coating thickness (to keep submerged when crossing rivers, lakes and estuaries) I calculated with a few lines of Fortran ... which I believe is still doing the job it was designed to do.
I strongly believe the fundimental point that the dir() function needs the required switches or an sdir (Super Dir) function is implemented.
My dream language to use was Cobal for so many reasons. Brilliant for combining logic and data structures (but geared for large scale data processing).

댓글을 달려면 로그인하십시오.


Matt O'Brien
Matt O'Brien 2023년 5월 8일
I am keen to supply feedback asap .... realised I needed to run the script in a Mac environment...
I copied the struct output from your script above into a table and saved to Excel.
With the test data I currently have on the card / card reader ... I have approx 700 lines of files/folders...
My initial dive into this is encouraging... with a little twist...
The folders, listed in these screen grabs, I am keen to exclude .... It looks like the script has successfully excluded these folders but left the files (or some of them) from within these folders. I only found these 3 examples.
I need to do a more thorough job of checking the test data and maybe testing a few other scenarios (eg different cameras). I may be missing some outliers in the other 700 rows, but initial inspection is looking very promising.
No need to try and tweak the script at this point. I will revert when I am comfortable I have digested the results.
I may need to get the list of 'hidden directories' and then specifically exclude / ignore the content of this directories.
(Ps1. Just FYI. there were dot and double dot folders included in the list ... which I am comfortable getting rid of.)
(Ps2. I will try to acquire a better grasp of the system 'find' command).

Matt O'Brien
Matt O'Brien 2023년 5월 9일
Just a quick update.
I am getting very confusing results. While the system Find results were initially promising, the MatLab dir command is now giving me identical results as using the System find command, as per the the script above. Exactly the same number of files / directories returned by both (ie 676, so a decent volume of data). I expect the MatLab dir command would include all the hidden folders.... but now... they are excluded ?????
My suspicision (worry) is that setting the option (in Finder) to display or hide hidden objects is having an effect on the respective find and dir commands when executed from MatLab. I need to check this further. If true, this is a disaster.
The second point of confusion is the following scenario, hinted in a note above.
Sony creates a hidden AV-Info directory (might be spelled wrong, writing on my ipad). This contains several files. Both Dir and Find lists do not include the folder name, but do include the folder files. My simple assumption is that the folder is flagged on the system as hidden but the respective files in the folder are flagged as visible. If so, it means that I have to specifically identify folders which are hidden and then remove all their contents from the list supplied via Dir or Find.
I need to dig deeper.
This is horrendously time consuming... I am not sure at what point I give up. I will continue for the moment.. but growing weary.

Matt O'Brien
Matt O'Brien 2023년 5월 9일
I am posting this... just in case there is interest ...I do not expect anyone to dig thru this stuff.
I found a glitch above and have completed a detailed comparison of the List genberated by MatLab Dir and System Find.
The result is close to the desired ... but there are a few glitches.
I am attaching an Excel spreadsheet which has a detailed line by line comparison of both lists, where I have commented on the differences (most at top and bottom of the list).
I am also enclosing a pdf with a few screen grabs, incl a screen grab of most of the folders expaned on the SD card, using Finder (and showing hidden items).
I need to digest this myself.... but looks like the Find list is close but will need to exclude visible files/folders stored in hidden folders (which may be several folders deep... ie the parent folder maybe visible but the parent of the parent may be hidden).
I will leave this for a few hours now and will review myself with a fresher pair of eyes.

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

태그

제품


릴리스

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by