How to change a specific line in a text file?
Show older comments
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
More Answers (2)
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
Bhaskar Banerjee
on 24 Aug 2018
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.
Marcos dos Santos
on 12 Mar 2021
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.
kH
on 18 Feb 2022
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
Walter Roberson
on 18 Feb 2022
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.
Luis Reig Buades
on 2 Mar 2022
\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
Walter Roberson
on 3 Mar 2022
data{1}{I} = regexprep(ReplaceString, '\\n', '\n'); % replace with this string
Allan
on 22 Sep 2022
good stuff! thank you ;)
Walter Roberson
on 11 Feb 2013
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
Walter Roberson
on 12 Mar 2021
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);
Categories
Find more on Characters and Strings 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!