How to delete the words/characters from a .txt file?
39 views (last 30 days)
Show older comments
I have data from a load cell that was written with uncessary characters in a .txt file (Attached). I only need the numbers from the data. Is there anyway to filter the words out? It would be even better if I could then convert that into a .csv file.
For example:
First line says
" Load_Cell_1==51.127 N -82.489 N -73.474 N -0.6313 Nm -0.2440 Nm -1.2160 Nm "
I want it to read
"51.127, -82.489, -73.474, -0.6313, -0.2440, -1.2160"
0 Comments
Accepted Answer
Voss
on 1 Apr 2022
Here's one way to get just the numbers out, which you can then do whatever you want with, including writing to a csv file (using, e.g., writematrix):
% open, read, and close the file:
fid = fopen('loadcell_data.txt');
data = fread(fid,'*char').';
fclose(fid);
% split the text on '==' and 'Nm':
data = split(data,{'==' 'Nm'});
% remove empty element after final 'Nm':
if isempty(data{end})
data(end) = [];
end
% reshape to four columns:
data = reshape(data,4,[]).';
% now the second column of 'data' contains the first four
% columns of numbers in the file, and that still needs
% to be split on 'N' (couldn't do it before because 'Nm'
% also contains 'N').
% split the second column on 'N', combine with columns
% 3 and 4, and convert everything to double:
data = str2double([split(data(:,2),'N') data(:,[3 4])])
0 Comments
More Answers (2)
per isakson
on 1 Apr 2022
Edited: per isakson
on 2 Apr 2022
fid = fopen( 'loadcell_data.txt' );
cac = textscan( fid, '%*[^=]==%f%*s%f%*s%f%*s%f%*s%f%*s%f%*s' );
fclose( fid );
num = cell2mat( cac );
num(1:3,:)
And
writematrix( num, 'loadcell.csv' ) % or csvwrite()
0 Comments
DGM
on 1 Apr 2022
There are probably faster or more robust ways, but here's one way.
alltext0 = fileread('loadcell_data.txt');
alltext0 = split(alltext0,newline);
numbers = regexp(alltext0,'[\s=]([-\d\.]*) Nm?','tokens');
numbers = vertcat(numbers{:});
numbers = cellfun(@str2double,numbers);
csvwrite('loadcell_data_modified.csv',numbers)
0 Comments
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!