필터 지우기
필터 지우기

how to replace a specific line in a text file with user data?

조회 수: 3 (최근 30일)
taimour sadiq
taimour sadiq 2023년 10월 30일
댓글: taimour sadiq 2023년 11월 2일
clear
Messege = 'Hello';
fileID = fopen('SampleFile.txt', 'rt');
textLine = fgetl(fileID);
lineCounter = 1;
while ischar(textLine)
fprintf('%s\n', textLine)
if startsWith(textLine, 'second line')
textLine = Messege % i want to replace this line with messege
disp('Done')
break
end
textLine = fgetl(fileID);
lineCounter = lineCounter + 1;
end
fclose(fileID);
my sample file contains three line data only "first line" "second line" "third line"... i want to replace my hello messge with line starts with string "second line".. code is running fine and display msg 'done' but gives error on messge line
>> Unable to perform assignmentbecause brace indexing is not supported for variable of this type <<
  댓글 수: 2
Les Beckham
Les Beckham 2023년 10월 30일
When I run your code I see no errors. It is not clear what you are really trying to do. Do you wish to change the contents of the file on disk?
Messege = 'Hello';
fileID = fopen('SampleFile.txt', 'rt');
textLine = fgetl(fileID);
lineCounter = 1;
while ischar(textLine)
fprintf('%s\n', textLine)
if startsWith(textLine, 'second line')
textLine = Messege % i want to replace this line with messege
disp('Done')
break
end
textLine = fgetl(fileID);
lineCounter = lineCounter + 1;
end
first line second line
textLine = 'Hello'
Done
fclose(fileID);
taimour sadiq
taimour sadiq 2023년 10월 30일
yes i wish to change the contents of the file on disk... Voss Code Works Fine

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

채택된 답변

Voss
Voss 2023년 10월 30일
input_file = 'SampleFile.txt';
output_file = 'SampleFile_modified.txt';
dbtype(input_file)
1 first line 2 second line 3 third line
Messege = 'Hello';
old_messege = 'second line';
L = readlines(input_file);
L(startsWith(L,old_messege)) = Messege;
writelines(L,output_file);
dbtype(output_file)
1 first line 2 Hello 3 third line
  댓글 수: 3
Walter Roberson
Walter Roberson 2023년 11월 2일
input_file = 'SampleFile.txt';
output_file = 'SampleFile_modified.txt';
dbtype(input_file)
1 first line 2 second line 3 third line
Messege = 'Hello';
old_messege = 'second line';
L = string(regexp(fileread(input_file), '\r?\n', 'split'));
L(startsWith(L,old_messege)) = Messege;
[fid, msg] = fopen(output_file, 'w');
if fid < 0
error('failed to open output file "%s" because "%s"', output_file, msg);
end
fwrite(fid, strjoin(L, newline));
fclose(fid)
ans = 0
dbtype(output_file)
1 first line 2 Hello 3 third line

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Audio and Video Data에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by