首页 > 其他分享 >写一个MATLAB脚本删除一个.m文件的所有注释,输出到一个新.m文件,文件名加上_modified后缀,用户可以自己决定是否保留空行

写一个MATLAB脚本删除一个.m文件的所有注释,输出到一个新.m文件,文件名加上_modified后缀,用户可以自己决定是否保留空行

时间:2023-12-26 14:03:19浏览次数:32  
标签:文件 end modified quotes fprintf MATLAB file line empty

请注意,这个脚本仅处理了最简单的情况,真正的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);



标签:文件,end,modified,quotes,fprintf,MATLAB,file,line,empty
From: https://blog.51cto.com/u_15247503/8982882

相关文章

  • LiveGBS流媒体平台GB/T28181常见问题-配置国标流媒体服务日志文件个数及记录时长配置l
    LiveGBS流媒体平台GB/T28181常见问题-如何配置国标流媒体服务日志文件个数及记录时长1、日志文件2、配置日志文件个数及记录时间3、配置日志文件路径4、相关问题4.1、如何关闭信令日志?5、搭建GB28181视频直播平台1、日志文件部署LiveGBS后,LiveCMS和LiveSMS的解压目录下都个l......
  • VS2019,无法启动程序xxx.exe,系统找不到指定的文件,重新生成解决方案报错
     调试程序报错如图一、尝试重新生成解决方案二、如果生成解决方案也报错,重新安装.netSDK本人所用为VS2019,.net5,到官网下载.net5的SDK重新安装后,恢复正常,重新生成成功,启动调试成功。.net各版本下载地址:https://dotnet.microsoft.com/en-us/download/dotnet.net5下载地址:h......
  • JavaWeb - Day11 - 案例 - 员工管理、文件上传、修改员工、配置文件
    01.案例-员工管理-新增员工前面我们已经实现了员工信息的条件分页查询以及删除操作。关于员工管理的功能,还有两个需要实现:新增员工修改员工首先我们先完成"新增员工"的功能开发,再完成"修改员工"的功能开发。而在"新增员工"中,需要添加头像,而头像需要用到"文件上传"技......
  • HTML5 文件上传的2种方式
    以前上传文件需要提交Form表单。HTML5方式上传文件,可以通过使用FormData类模拟Form表单提交,从而实现无刷新上传文件。 假设有一个文件选择框<inputtype="file"name="pic"id="pic"accept="image/gif"/>有下面2种方式上传文件:1、XMLHttpRequest(有进度事件)varfiles=d......
  • Linux配置NFS文件共享
    一、NFS简介NFS是NetworkFileSystem的缩写,是一种分布式文件系统协议,用于在计算机网络上共享文件。它允许客户端计算机通过网络远程访问和处理远程服务器上的文件和目录。NFS最初由SunMicrosystems开发并在1984年发布,被设计为可在不同操作系统和硬件平台之间共享文件。它基于客户......
  • 宝塔文件分析
    宝塔文件分析 宝塔登录密码加密方式此处分析的实验环境为宝塔版本:免费版7.6.0tools.py调用set_panel_pwd()函数设置密码result=sql.table('users').where('id=?',(1,)).setField('password',public.password_salt(public.md5(password),uid=1))此处看到使用了public.......
  • pdf文件修改
    packagemainimport( "fmt" docx"github.com/lukasjarosch/go-docx")funcmain(){ replaceMap:=docx.PlaceholderMap{ "wilson1":"wilson", "wilson":"4205234243", "......
  • 解决adb传文件中文名问题
    @echooffsetlocalenabledelayedexpansionREM路径后面记得不要加斜杠set目标路径=/sdcard/01tmpecho目标路径:%目标路径%echo=set有连接=Falsefor/F"tokens=*skip=1"%%iin('adbdevices')doset有连接=Truesetn=10setstr=abcdefghijklmnopqrstuvwxyz012......
  • Linux文件系统(以ext2为例)
    所有的计算机程序都需要存储和检索信息。长期存储信息有三个基本要求:能够存储大量信息。存储必须持久化。多个进程可以并发访问这些信息。这些任务一般由磁盘来进行。虽然固态硬盘在近年逐渐流行,但传统磁盘依然是存储大量数据的首选。本文只针对磁盘,不对固态硬盘进行讨论。使用磁盘......
  • 使用git工具将本地文件上传到github仓库
    1、先创建一个文件夹2、gitinit:把文件夹变成git可管理的仓库3、gitadd.:“.”表示当前文件夹下所有内容都提交,也可以通过gitaddFileName/FolderName提交指定的文件或文件夹把文件添加到缓存区4、gitstatus:查看现在的状态5、gitcommit-m"description":把文件提交的本地......