How to change a specific line in a text file?

Hi
I have a text file, where different forms of content exist, data or strings or symbols, i need to change a specific line (it's only a number), i know its position (69 line)
Is there any way to do so?

 Accepted Answer

ChristianW
ChristianW on 11 Feb 2013
Edited: ChristianW on 11 Feb 2013
  1. Loading txt into a cell.
  2. Then do whatever you want with the cell. In this example, line 69 will be 99.
  3. Then write the cell into a txt.
% Read txt into cell A
fid = fopen('test.txt','r');
i = 1;
tline = fgetl(fid);
A{i} = tline;
while ischar(tline)
i = i+1;
tline = fgetl(fid);
A{i} = tline;
end
fclose(fid);
% Change cell A
A{69} = sprintf('%d',99);
% Write cell A into txt
fid = fopen('test2.txt', 'w');
for i = 1:numel(A)
if A{i+1} == -1
fprintf(fid,'%s', A{i});
break
else
fprintf(fid,'%s\n', A{i});
end
end

5 Comments

If you are going to use this method (presumes that the file is not too big)
A = regexp( fileread('test.txt'), '\n', 'split');
A{69} = sprintf('%d',99);
fid = fopen('test2.txt', 'w');
fprintf(fid, '%s\n', A{:});
fclose(fid);
I like that regexp fileread load. fwrite doesnt have a format input, i guess its meant to be fprintf? While fprintf alone doing a \n new line at the fileend.
Thanks, I've fixed the fwrite()
Thanks, it works perfectly.
Dear community,
I have many txt files that uses a tab delimiter. I have to change the content between the 17th and 18th tab delimiter of all my files. This is one the data inside the file:
_______
Data file generated on Tue Aug 30 12:40:29 2022
A B C D E F G H I J K L M N O P Q R S T U
1 2.00000 2.00000 0.00000 1.00000 28.00000 64.00000 88.00000 1.20000 275.00000 50.00000 30.00000 165.00000 850.00000 500.00000 0.00000 10.00000 10.00000 15.00000 0,0,0,0, 0,0,0,0, false
_______
So I have to change the value for the variable Q (in this case 10.0000) for a specific value. However, some of my files have a different pattern for numbers, instead of 10.00000 it is only 10, what makes the counting characters unfeasible. Furthermore, after some delimiters there are spaces. Then, I decided to count the tab delimeters, and change the content between the 17th and 18th delimiter to solve my problem, that I don't know if it will work. This is my code so far.
A = regexp(fileread(myfile), '\n', 'split'); %upload my file to a cell array
B = strfind(A{4}, sprintf('\t')); %takes the cell 4 in the array and finds where I have tab delimiters
C = B{4}(17)+1:B{4}(18)-1; %select the content between the 17th and 18th tab delimiters
Please, can somebody help me???

Sign in to comment.

More Answers (2)

Abdul
Abdul on 11 Aug 2015
Edited: Walter Roberson on 17 Jul 2018
I have written a function that scans for the specified SearchString in the InputFile and replaces it with the ReplaceString in the OutputFile. If the same file is specified as both the input and output file, the file is overwritten.
function [] = func_replace_string(InputFile, OutputFile, SearchString, ReplaceString)
%%change data [e.g. initial conditions] in model file
% InputFile - string
% OutputFile - string
% SearchString - string
% ReplaceString - string
% read whole model file data into cell array
fid = fopen(InputFile);
data = textscan(fid, '%s', 'Delimiter', '\n', 'CollectOutput', true);
fclose(fid);
% modify the cell array
% find the position where changes need to be applied and insert new data
for I = 1:length(data{1})
tf = strcmp(data{1}{I}, SearchString); % search for this string in the array
if tf == 1
data{1}{I} = ReplaceString; % replace with this string
end
end
% write the modified cell array into the text file
fid = fopen(OutputFile, 'w');
for I = 1:length(data{1})
fprintf(fid, '%s\n', char(data{1}{I}));
end
fclose(fid);

7 Comments

Thanks a lot for that, One question what if there are multiple instances of "SearchString", and I wish to change only a few of them? Is there a way to specify particular line numbers?
THanks.
Hey Bhaskar. I did it by defining SearchString and ReplaceString as cells. SearchString = {str1,str2, etc.}; ReplaceString = {str1,str2, etc.}. I created for loop that calls the function.
SearchString = {str1,str2, etc.};
ReplaceString = {str1,str2, etc.}
for ii=1:length(SearchString)
func_replace_string(InputFile, OutputFile, SearchString{ii}, ReplaceString{ii})
end
function [] = func_replace_string(InputFile, OutputFile, SearchString, ReplaceString)
% change data [e.g. initial conditions] in model file
% InputFile - string
% OutputFile - string
% SearchString - string
% ReplaceString - string
% read whole model file data into cell array
fid = fopen(InputFile);
data = textscan(fid, '%s', 'Delimiter', '\n', 'CollectOutput', true);
fclose(fid);
% modify the cell array
% find the position where changes need to be applied and insert new data
for I = 1:length(data{1})
tf = strcmp(data{1}{I}, SearchString); % search for this string in the array
if tf == 1
data{1}{I} = ReplaceString; % replace with this string
end
end
% write the modified cell array into the text file
fid = fopen(OutputFile, 'w');
for I = 1:length(data{1})
fprintf(fid, '%s\n', char(data{1}{I}));
end
fclose(fid);
end
I hope this helps.
how to add new line in the data file ?
Example :
before add new line after add new line
data=1 data=1
a a
s newline
4 s
4
If it is a text file, then often the easiest way is to use one of the old command line editors such as the unix editor 'sed' .
Unfortunately the underlying representation of text files by all modern operating systems does not permit going in and directly inserting something according to line number. Text files are just streams of characters, so to insert another character requires re-writing the rest of the file.
filename = 'AppropriateName.txt';
newfilename = 'AppropriateNewName.txt';
lines = readlines(filename);
lines = [lines(1:2); {newline}; lines(3:end)];
[fid, msg] = fopen(newfilename);
if fid < 0; error('Failed to open file "%s" because: "%s"', newfilename, msg); end
fprintf(fid, '%s\n', lines);
fclose(fid);
Note: this code could have the effect of adding an extra blank line at the end. It can be tricky to tell the difference between a file that ends in a blank line, compared to a file that ends with a newline character.
\n is not adding a new line in ReplaceString, how do I go about replacing one line with several lines?
I want '*Include, Input = NEPER_sections.inp\n*End Part\n*Include, Input = NEPER_materials.inp' to show as:
*Include, Input = NEPER_sections.inp
*End Part
*Include, Input = NEPER_materials.inp
but it shows as:
*Include, Input = NEPER_sections.inp\n*End Part\n*Include, Input = NEPER_materials.inp
data{1}{I} = regexprep(ReplaceString, '\\n', '\n'); % replace with this string
good stuff! thank you ;)

Sign in to comment.

sed. Or perl. Or python.
Or you could open the input file, open the output file, copy 68 lines from the input to the output, then read one line from input and write out the replacement output instead of the input line, then read the rest of the lines from input and copy them to output; finally, close both files.
There are fancier ways using (e.g.,) textscan() to read a bunch of lines at once.
Really, though, if you are on Linux or OS-X, I recommend using the system utility sed.
system('sed -e "69s/.*/31419/" < OLDFILE > NEWFILE')
here the 69 is the line you want changed and the 31419 is the new value you want put in

1 Comment

These days, MATLAB also supports
readlines(filename)
which reads the file into a cell array of character vectors, one per line. You can then make whatever changes to the line (using {} indexing) and write the lines out again. For example,
S = readlines('test.txt');
S{69} = regexprep(S{69}, '-1', '31419'); %file says -1 change it to 31419
[fid, msg] = fopen('new_test.txt', 'w');
if fid < 1;
error('could not write output file because "%s"', msg);
end
fwrite(fid, strjoin(S, '\n'));
fclose(fid);

Sign in to comment.

Categories

Community Treasure Hunt

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

Start Hunting!