MATLAB: Automatic text editor for reformatting GCODE files

text filetext;textscan

I have a problem where I need to convert GCODE files (essentially .txts) to the correct format. Essentially I need to get rid of E-codes from a line (without otherwise altering it) and frame lines that had them with M-codes.
IE If a file contained the following text
G1 X0 Y0
G1 X95.522 Y98.212
G1 X95.669 Y98.424 E3.08527
G1 X95.669 Y104.331 E4.73024
G1 X104.331 Y95.669 E8.14186
G1 X104.331 Y101.576 E9.78683
G1 X101.576 Y104.331 E10.87210
G1 X125.325 Y104.333
G1 X101.576 Y106.221
I would like to turn it into
G1 X0 Y0
G1 X95.522 Y98.212
M182;
G1 X95.669 Y98.424
G1 X95.669 Y104.331
G1 X104.331 Y95.669
G1 X104.331 Y101.576
G1 X101.576 Y104.331
M183;
G1 X125.325 Y104.333
G1 X101.576 Y106.221
So basically look for blocks of lines of the form "G1 X<number> Y<number> E<number>" insert "M182;" before the first one and "M183;" after the last one. Then go through the document and delete everything of the form "E<number>"
Here's a pseudocode of how I think it would work
open file
n=0;
format="G1 X<number> Y<number> E<number>"
for all lines one by one
if line = format and n=0
create line above with M182
set n=1
end
if line != format and n=1
create line above with M183
set n=0
end
if textinline="E<number>"
delete textinline
end
end

Best Answer

I figured it out.
filename='1cm_x_1cm_block.gcode';
output=strcat('converted',filename);
fid = fopen(filename);
look = ('G\S+\sX\S+\sY\S+\sE\S+');
count=1;
linelist = [0];
listcount=1;
while ~feof(fid)
tline = fgetl(fid);
if regexp(tline,look);
linelist(listcount)=count;
listcount=listcount+1;
end
count=count+1;
end
frewind(fid);
count=1;
toggle=0;
out = fopen(output, 'wt' );
while ~feof(fid)
if ismember(count,linelist)&&toggle==0;
toggle=1;
fprintf(out,'%s\n','M182;');
elseif ~ismember(count,linelist)&&toggle==1;
toggle=0;
fprintf(out,'%s\n','M183;');
else
tline = fgetl(fid);
fprintf(out,'%s\n',regexprep(tline,'E\S+\s?',''));
%fprintf(out,'%s\n',regexprep(tline,'(E-?)([0-9]){0,}.?(\d+)\s?',''));
count=count+1;
end
end