如何通过Matlab更改YAML文件中的单个值?

问题描述 投票:0回答:1

我有以下 YAML 文件描述:

messageQueue:
  queue:
    name: "username"          
    create: true            
    durable: false         
    exclusive: false        
    autoDelete: false       
  host: 'localhost'         
  port: 5672

但是,我想通过 MATLAB 仅更改 yaml 文件的“名称”字段,然后使用另一个预构建的函数运行该文件。

我该怎么做?

谢谢, 德鲁夫

matlab yaml rabbitmq
1个回答
0
投票

您可以使用正则表达式来查找

name:
行,替换字符串,并重建 yml。仅当您的 yaml 不太复杂时才应使用此方法,否则您将需要处理一组越来越困难的边缘情况...

我在下面的代码中添加了注释来解释每个步骤,包括我的正则表达式模式的逻辑

% 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:
% - start of line, then one or more spaces
% - then the keyword `name:`
% - 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 );
© www.soinside.com 2019 - 2024. All rights reserved.