Filter löschen
Filter löschen

Find text in multiple functions at once

6 Ansichten (letzte 30 Tage)
Lina Koronfel
Lina Koronfel am 15 Feb. 2023
Beantwortet: Harshit Saini am 15 Feb. 2023
Is there a way to find and replace text that repeat in multiple functions that are saved in the same folder? I currently have to open every function one by one and find/replace the desired text. Is there a more efficient way to find the text that repeats in all functions within the same folder?

Antworten (1)

Harshit Saini
Harshit Saini am 15 Feb. 2023
Yes, there is a way to find and replace text that repeats in multiple MATLAB functions saved in the same folder. You can use the "dir" function to get a list of all the functions in the folder, and then use a loop to read each function, find and replace the desired text, and then save the changes back to the original file.
Here's an example code snippet that shows how to do this:
folder = 'path/to/your/folder';
searchText = 'text-to-find';
replaceText = 'text-to-replace';
% get a list of all MATLAB files in the folder
fileList = dir(fullfile(folder, '*.m'));
% loop through each file in the folder
for i = 1:numel(fileList)
filename = fullfile(folder, fileList(i).name);
% read the contents of the file
fid = fopen(filename, 'r');
fileContents = fread(fid, '*char')';
fclose(fid);
% replace the text in the file contents
newContents = strrep(fileContents, searchText, replaceText);
% write the updated contents back to the file
fid = fopen(filename, 'w');
fwrite(fid, newContents);
fclose(fid);
end
In this code, “folder” is the path to the folder containing the MATLAB functions you want to update. "searchText" is the text you want to find, and "replaceText" is the text you want to replace it with. The code uses the “dir” function to get a list of all the MATLAB files in the folder with a .m extension. Then, it loops through each file in the list, reads its contents using “fread” function, replaces the desired text using the “strrep” function, and saves the updated contents back to the original file using the “fwrite” function.

Kategorien

Mehr zu File Operations finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by