写一个MATLAB脚本删除一个.m文件的所有注释和空行,输出到一个新.m文件,文件名加上_modified后缀

发布时间 2023-12-19 10:53:48作者: yhm138

请注意,这个脚本仅处理了最简单的情况,真正的Matlab代码可能包含更复杂的结构,如多行字符串、嵌套的字符串、转义字符等,处理这些情况可能需要更复杂的逻辑。

% Specify the input .m file name
inputFileName = 'originalScript.m';
outputFileName = [inputFileName(1:end-2) '_modified.m']; % Assumes .m extension

% 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))
            % If the line is empty, skip it
            continue;
        else
            % Remove inline comments, considering the possibility of '%' in strings
            % Find all occurrences of single quote
            quotes = strfind(line, '''');
            % 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 all(arrayfun(@(o, c) i < o || i > c, openQuotes, closeQuotes))
                    % 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
            % If the line is not empty after removing comments, write it to the output file
            if ~isempty(line)
                fprintf(fidOutput, '%s\n', line);
            end
        end
    end
catch ME
    % If an error occurs, display an error message
    fprintf('An error occurred: %s\n', ME.message);
end

% Close the files
fclose(fidInput);
fclose(fidOutput);

% Notify the user
fprintf('The file "%s" has been processed. All comments and empty lines were removed.\n', inputFileName);
fprintf('The modified file is saved as "%s".\n', outputFileName);