How do I find a file containing a particular string in a given directory in MATLAB 7.13(R2011b)?
90 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I want to find the file that contains the string 'xxx' from a particular directory. How do I do the search?
Réponse acceptée
MathWorks Support Team
le 29 Mar 2013
You can achieve this in MATLAB by navigating to the “Find Files…” option under the “Edit” tab. You can enter the required string and search for the string in the files in a particular directory and also choose to search in the subfolders.
You can also open “Find Files…” window with the following keystrokes Ctrl+Shift+F.
If you would like to do this programmatically, the following is a simple script which performs this:
directory = '<Directory path>'; % Full path of the directory to be searched in
filesAndFolders = dir(directory); % Returns all the files and folders in the directory
filesInDir = filesAndFolders(~([filesAndFolders.isdir])); % Returns only the files in the directory
stringToBeFound = '<Specify the string you would like to be searched for>';
numOfFiles = length(filesInDir);
i=1;
while(i<=numOfFiles)
filename = filesInDir(i).name; % Store the name of the file
fid = fopen(filename);
while(~feof(fid)) % Execute till EOF has been reached
contentOfFile = fgetl(fid); % Read the file line-by-line and store the content
found = strfind(contentOfFile,stringToBeFound); % Search for the stringToBeFound in contentOfFile
if ~isempty(found)
foundString = strcat('Found in file------', filename);
disp(foundString);
break;
end
end
fclose(fid); % Close the file
i = i+1;
end
Please note that this script does not search for the term in the sub-directories.
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur File Operations dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!