2016-06-26 50 views
1

我創建一個測試標準模板獲取評論日期時間和計算機名

% 
% Description: 
% 
    Author = ['Author : ' getenv('computername')] 
% 
    Date =['Date : ' datestr(datetime('now' ,'Format','d-MMM-y'))] 
% 
% Comment: 
% 
%------------------------------------------------------------------------- 
%% do something 
%------------------------------------------------------------------------- 

和我通話功能是

function [] = newmfile(V) 
V = [V '.m'] 
copyfile('StandardTemplate.m',V) 
edit(V) 

所以當一個人寫

newmfile Test 

它創建了我創建的模板的新文件,但現在的問題是我知道如何獲取當前的計算機名稱和日期因爲我已經寫了,但我如何使它所以它出現在評論和「作者」和「日期」作爲一個字符串得到上面的代碼的結果,所以我得到的模板

% 
% Description: 
% 
% Author : This Computer 
% 
% Date : 26-Jun-2016 
% 
% Comment: 
% 
%------------------------------------------------------------------------- 
%% do something 
%------------------------------------------------------------------------- 

更新: 我曾嘗試創建通過一個文本文件,它的工作原理,但仍然是一個更好的解決方案,將不勝感激

function [] = newmfile(V) 
V = [V '.m']; 
per = '%'; 
Author = [ getenv('computername')]; 
Date =['Date : ' datestr(datetime('now' ,'Format','d-MMM-y'))]; 
copyfile('StandardTemplate.txt','TempTextfile.txt') 
replaceLine = 4; 
fileID = fopen('TempTextfile.txt','r+'); 
for k=1:(replaceLine-1); 
    fgetl(fileID); 
end 
fseek(fileID,0,'cof'); 
fprintf(fileID,'%s Author: %s\n%s\n%s %s\n%s\n%s',per,Author,per,per,Date,per,per); 
fclose all; 
copyfile('TempTextfile.txt',V) 
delete('TempTextfile.txt') 
edit(V) 

回答

1

你可以使用自己的模板語法來指示該模板加載應作出什麼替代創建原始模板。在這裏,我剛剛使用$command$來指示應該運行的命令,以用這些命令的結果替換命令。

% 
% Description: 
% 
% Author: $getenv('computername')$ 
% 
% Date : $datestr(datetime('now' ,'Format','d-MMM-y'))$ 
% 
% Comment: 
% 
%------------------------------------------------------------------------- 
%% do something 
%------------------------------------------------------------------------- 

然後,你就用regexprep將匹配任何$command$外觀,然後,而不是做一個靜態的字符串替換過程中,我們使用了${function_to_run}語法替換字符串和裏面我們把它評估匹配(不包括任何一端的$)並返回要插入字符串的結果。

fid = fopen('template.m', 'r'); 
contents = fread(fid, '*char')'; 
fclose(fid); 

% Replace all strings between $ and $ with their evaluated version 
newcontents = regexprep(contents, '\$(.*?)\$', '${eval($1)}'); 

% Write to new file 
fid = fopen('destination.m', 'w'); 
fwrite(fid, newcontents); 
fclose(fid); 
+0

謝謝!我會試試這個 – Umar