Remove leading blank space from specific lines in .txt files

4 views (last 30 days)
Hi. I need help removing the blank spaces in front of some of the lines in text files.
I want to remove the indent in front of the numbers, but want to leave the indent in front of the words. The begining numbers are the same(i.e., 2500.0, 5000.0, 10000.0, 20000.0, 50000.0), but the numbers following are different. In other words, every line is unique, making it difficult to use something like regexp() to find and replace for large data sets.
For example I have:
Name,proj1;
Edition,52;
Start;
Variable,1;
DataReg,1,0.00,0.00,0.00;
DataAng,1,00.0,00.0;
Area,520.00;
2500.0,180.047,180.997,190.946;
5000.0,80.124,80.552,80.979;
10000.0,40.039,40.252,40.465;
20000.0,20.090,20.200,20.310;
DataAng,2,00.0,00.0;
Area,690.00;
2500.0,130.687,140.407,150.128;
5000.0,70.008,70.377,70.746;
10000.0,30.675,30.868,40.062;
20000.0,10.906,20.006,20.107;
Area,710.00;
2500.0 .......
Also, down the road I may want to remove space in front of selected words too (i.e., Area)

Accepted Answer

Mathieu NOE
Mathieu NOE on 10 Feb 2021
hello
my suggestion below , tested on following text (I added a last section for my testing purposes)
Start;
Variable,1;
DataReg,1,0.00,0.00,0.00;
DataAng,1,00.0,00.0;
Area,520.00;
2500.0,180.047,180.997,190.946;
5000.0,80.124,80.552,80.979;
10000.0,40.039,40.252,40.465;
20000.0,20.090,20.200,20.310;
DataAng,2,00.0,00.0;
Area,690.00;
2500.0,130.687,140.407,150.128;
5000.0,70.008,70.377,70.746;
10000.0,30.675,30.868,40.062;
20000.0,10.906,20.006,20.107;
Area,710.00;
2500.0,130.687,140.407,150.128;
5000.0,70.008,70.377,70.746;
10000.0,30.675,30.868,40.062;
20000.0,10.906,20.006,20.107;
Location,710.00;
2500.0,130.687,140.407,150.128;
5000.0,70.008,70.377,70.746;
10000.0,30.675,30.868,40.062;
20000.0,10.906,20.006,20.107;
Filename = 'Document1.txt';
fid = fopen(Filename);
tline = fgetl(fid);
selected_words = {'Area'}; % test 1
% selected_words = {'Area','Location'}; % test 2
k = 0;
while ischar(tline)
% check if first string is numeric and deblank
out = split(tline,',');
k = k + 1;
new_line{k} = tline;
if ~isempty(str2num(out{1}))
new_line{k} = strip(tline,'left'); % remove blanks left side (leading)
else
for ci = 1:numel(selected_words)
if contains(tline,selected_words(ci))
new_line{k} = strip(tline,'left'); % remove blanks left side (leading)
end
end
end
tline = fgetl(fid);
end
fclose(fid);
writecell(new_line', 'out.txt',"QuoteStrings",0);

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Tags

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!