-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregexprep_file.m
36 lines (30 loc) · 1.05 KB
/
regexprep_file.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function regexprep_file(inputFile, outputFile, searchRE, replaceString, varargin)
%% regexprep_file
% Run regexprep on each line of a text file
%
% Usage: regexprep_file(inputFile, outputFile, searchRE, replaceString)
% regexprep_file(inputFile, outputFile, searchRE, replaceString, vararginForRegexprep)
%
% Inputs:
% InputFile - string
% OutputFile - string
% SearchString - string
% ReplaceString - string
%
% Modified from: https://www.mathworks.com/matlabcentral/answers/62986-how-to-change-a-specific-line-in-a-text-file
assert(nargin && ~isempty(inputFile) && ~isempty(outputFile))
% read whole model file data into cell array
fid = fopen(inputFile);
data = textscan(fid, '%s', 'Delimiter', '\n', 'CollectOutput', true);
fclose(fid);
data = data{1};
% replace in each line
for iLine = 1:length(data)
data{iLine} = regexprep(data{iLine}, searchRE, replaceString, varargin{:});
end
% write the modified cell array into the text file
fid = fopen(outputFile, 'w');
for iLine = 1:length(data)
fprintf(fid, '%s\n', char(data{iLine}));
end
fclose(fid);