How do I find a file containing a particular string in a given directory in MATLAB 7.13(R2011b)?

83 visualizaciones (últimos 30 días)
I want to find the file that contains the string 'xxx' from a particular directory. How do I do the search?

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 29 de Mzo. de 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.

Más respuestas (0)

Categorías

Más información sobre File Operations en Help Center y File Exchange.

Productos


Versión

R2011b

Community Treasure Hunt

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

Start Hunting!

Translated by