필터 지우기
필터 지우기

Manipulate numbers in existing txt file

조회 수: 1 (최근 30일)
Stefan
Stefan 2017년 12월 18일
댓글: Stefan 2017년 12월 19일
Hi,
I want to manipulate numbers in a txt file which was created by catia. The txt file looks like this:
Catia puts a space between every string and float. For example I want to change 'l_overall (mm)' to 5000.
Thank you for your help!
  댓글 수: 1
Walter Roberson
Walter Roberson 2017년 12월 18일
I notice that there is a space between l_overall and (mm) and a space between w_overall and (mm) but no space between h_overall and (mm) . Is the actual file consistent about the space there or not?
Can we assume that the variables are always in exactly the same order and that we can assume that l_overall will be the first entry on the line (for example) ? Or is it necessary to match the strings to determine which column to make the change to ?
Is it possible that the fields are really tab delimited rather than space delimited ?

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2017년 12월 19일
fid = fopen('Table1.txt', 'rt');
colnames = fgetl(fid);
colvals = fscanf(fid, '%f', [1 inf]);
fclose(fid)
colvals(1) = 5000;
fid = fopen('newTable1.txt', 'wt');
fprintf(fid, '%s\n', colnames);
fprintf(fid, '%g\t', colvals(1:end-1));
fprintf(fid, '%g\n', colvals(end));
fclose(fid)
  댓글 수: 1
Stefan
Stefan 2017년 12월 19일
Thank you very much! I found my mistake.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

YT
YT 2017년 12월 18일
I don't know if I understand the question correctly, but if you want to change 'l_overall (mm)' to '5000' in your text file, you can do something like this (I assumed that your text file looks something like the test.txt I attached)
clear all;
fileID = fopen('test.txt');
C = textscan(fileID,'%s','delimiter','\n');
fclose(fileID);
C{:} = strrep(C{:},'l_overall (mm)','5000'); %replacing 'l_overall (mm)' by '5000'
writetable(cell2table(C{:}),'updated_data.txt','WriteVariableNames',0) %writing the new data
  댓글 수: 3
Walter Roberson
Walter Roberson 2017년 12월 19일
You would get that textscan error if you provided the wrong filename to fopen()
Walter Roberson
Walter Roberson 2017년 12월 19일
"There is a space between every column header, unit and variable"
The delimiter between columns is tab, just as I had guessed.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by