How to modify any text file via MATLAB programmatically?

25 views (last 30 days)
Hi All
I need to modify text files with MATLAB, but the questions that I find offer ambiguous solutions, practically I don't understand the codes, shall someone share a clearly explained code, to know how to edit a text file (with some txt and numbers already written) using MATLAB?
The best example comes to my mind is that to look up for a specific word and/or number in a text file and once found modify/copy thata into/via MATLAB.
In a better example if there's a line starting with a specific word after which there's a number, how can I read that number like :
Line
Line
....
....
....
Specific word 127543
How can I read and copy the number to matlab?
  1 Comment
Jan
Jan on 6 Feb 2018
The question is not clear. "Edit" means usually opening a text file in an editor to apply manual changes. But because you are talking about code, I assume you mean to modify a text file programmatically. To suggest a reliable method, we need to know, what you want to replace by what. There is no general way to change something, but the main problem is how the parts to be changed are recognized. So please take the time to explain the details. I would be helpful also, if you post a link to the other solution and explain, what you find "ambiguous".

Sign in to comment.

Accepted Answer

Jan
Jan on 7 Feb 2018
Str = splitstr(fileread(FileName). \n');
Key = 'Specific word';
match = strncmp(Str, Key, length(Key));
Now Str(match) contains all lines starting with the Key. Scanning them is easy.
% If it is one line only:
Value = sscanf(Str{match}, [Key, '%g']);
% If it occurs in multiple lines:
StrC = sprintf('%s*', Str{match});
Value = sscanf(StrC, [Key, '%g*']);

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!