写一个MATLAB脚本删除一个.m文件的所有注释,输出到一个新.m文件,文件名加上_modified后缀,用户可以自己决定是否保留空行
请注意,这个脚本仅处理了最简单的情况,真正的Matlab代码可能包含更复杂的结构,如多行字符串、嵌套的字符串、转义字符等,处理这些情况可能需要更复杂的逻辑。
clear all; close all; clc;
% Specify the input .m file name
inputFileName = 'originalScript.m';
outputFileName = [inputFileName(1:end-2) '_modified.m']; % Assumes .m extension
% User option to keep or remove empty lines
keepEmptyLines = true; % User sets this to false to remove empty lines
userInput = input('Do you want to keep empty lines? (y/n): ', 's');
if userInput == 'y'
keepEmptyLines = true;
elseif userInput == 'n'
keepEmptyLines = false;
else
error('Invalid input. Please enter y or n.');
end
fprintf('Keep empty lines option is set to %s.\n', mat2str(keepEmptyLines));
% Open the input file for reading
fidInput = fopen(inputFileName, 'r');
% Open the output file for writing
fidOutput = fopen(outputFileName, 'w');
% Check if the files are opened successfully
if fidInput == -1 || fidOutput == -1
error('Error opening files.');
end
try
% Read and process the file line by line
while ~feof(fidInput)
line = fgetl(fidInput); % Read a line from the input file
if isempty(strtrim(line)) && ~keepEmptyLines
% If the line is empty and user chose not to keep empty lines, skip it
continue;
else
% Remove inline comments, considering the possibility of '%' in strings
% Find all occurrences of single quote
quotes = strfind(line, '''');
if mod(length(quotes), 2) ~= 0
% If there's an odd number of quotes, ignore the last one
quotes(end) = [];
end
% Split the quotes into opening and closing pairs
openQuotes = quotes(1:2:end);
closeQuotes = quotes(2:2:end);
% Find the first '%' that is not between opening and closing quotes
percentSigns = find(line == '%');
for i = percentSigns
if isempty(openQuotes) || all(arrayfun(@(o, c) i < o || i > c, openQuotes, closeQuotes))
if i == 1 || line(i-1) ~= '.'
% This '%' is not inside a string, so it starts a comment
line = strtrim(line(1:i-1));
break; % Stop at the first comment
end
end
end
% If the line is not empty after removing comments, or if we keep empty lines, write it to the output file
if ~isempty(line) || keepEmptyLines
fprintf(fidOutput, '%s\n', line);
end
end
end
catch ME
% If an error occurs, display an error message and the line causing the error
fprintf('An error occurred: %s\n', ME.message);
fprintf('Error occurred at line: %s\n', line);
end
% Close the files
fclose(fidInput);
fclose(fidOutput);
% Notify the user
fprintf('The file "%s" has been processed.\n', inputFileName);
if keepEmptyLines
fprintf('Empty lines were kept.\n');
else
fprintf('All comments and empty lines were removed.\n');
end
fprintf('The modified file is saved as "%s".\n', outputFileName);