I have the following YAML file description:
messageQueue:
queue:
name: "username"
create: true
durable: false
exclusive: false
autoDelete: false
host: 'localhost'
port: 5672
However, I would like to change only the "name" field of the yaml file via MATLAB and then run the file with another pre-built function.
How can I do this ?
Thanks, Dhruv
You could use regular expressions to find the name:
line, replace the string, and reconstruct the yml. This should only be used if your yaml isn't too complex, otherwise you'll have an increasingly difficult set of edge cases to handle...
I've added comments to the below code to explain each step, including the logic for my regex pattern
% read in the entire yml as a char
yml = fileread('test.yml');
% define the new name to replace in the name field
newName = 'test';
% Find the start and end indicies in the char for the line following the pattern:
% ^\s+ start of line, then one or more spaces
% name: then the keyword `name:`
% \s* then zero or more spaces
% ".+" then one or more of any characters surrounded by double quotes
[a,b] = regexp( yml, '^\s+name:\s*".+"', 'once', 'lineanchors');
% Make new line by replacing the bit after the colon with the new name in quotes
name = sprintf('%s: "%s"', extractBefore(yml(a:b),':'), newName );
% Reconstruct the yml string from before and after then name line,
% with the modified name line in the middle
yml = [yml(1:a-1), name, yml(b+1:end)];
% Write to a new file
fid = fopen( 'testModified.yml', 'w' );
fprintf( fid, yml );
fclose( fid );
Perhaps an easier way is to invent some unique syntax for variables to replace, and use that instead of faffing around with regex
, for example if your original yaml was this:
messageQueue:
queue:
name: "$$USERNAME$$"
create: true
durable: false
Then you could just have the MATLAB code
yml = fileread('test.yml');
newName = 'test';
yml = strrep( yml, '$$USERNAME$$', newName );
Before writing back to a file in the same way (fopen
/fprintf
/fclose
).