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);
- Keys and values are separated by spaces (no matter how many).
- The pair key-value are divided by (at least) a new line.