[Matlab] Replace a parameter’s value inside text file

This is an old website post.

New post address:
https://www.pisciottablog.com/2019/07/07/matlab-replace-a-parameters-value-inside-text-file/
+++ This wordpress.com domain will not be kept up-to-date anymore+
+++ Please, use the new one (pisciottablog.com) ++++++++++++++++++

++++++++++++++++++++++++++++++++++++++++++++++++++++++++

++++++++++++++++++++++++++++++++++++++++++++++++++++++++

++++++++++++++++++++++++++++++++++++++++++++++++++++++++

++++++++++++++++++++++++++++++++++++++++++++++++++++++++

++++++++++++++++++++++++++++++++++++++++++++++++++++++++

++++++++++++++++++++++++++++++++++++++++++++++++++++++++

++++++++++++++++++++++++++++++++++++++++++++++++++++++++

++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Assuming we file.txt, which looks like this:

[HEADER-1]
KEY1 VALUE1
KEY2 VALUE2
KEY3 VALUE3

[HEADER-2]
KEY4 VALUE4
KEY5 VALUE5
KEY6 VALUE6
KEY7 VALUE7
KEY8 VALUE8

[HEADER-3]
...

Task: open file.txt in Matlab, change the value corresponding to KEY8 (which is “VALUE8”) to e.g. “NEW VALUE8” and save the new version as file_after.txt.

inputfile = fileread("file.txt");
outputfile = regexprep(inputfile, '(?<=KEY8\s+)(\S).*?(?=\n)', 'NET VALUE8\r');
fid = fopen('file_after.txt','w');
fprintf(fid, outputfile);
fclose(fid);

General assumptions:

  • Keys and values are separated by spaces (no matter how many).
  • The pair key-value are divided by (at least) a new line.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: