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

374 views (last 30 days)

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 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.

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Products


Release

R2011b

Community Treasure Hunt

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

Start Hunting!