replace a random number in a line of a text file

3 次查看(过去 30 天)
how can I replace random number (with 'randi()' commond) in a text file? for example I want replace "1.035" in the below line with a random number:
"x coordinate = 1.035"

采纳的回答

Walter Roberson
Walter Roberson 2021-9-30
In the below, the isunix() branch is to put in example text since I do not have a file to work with. In your actual code, you would just have the fileread() without the if isunix()
filename = 'example.txt';
outfilename = 'modified.txt';
if isunix()
S = sprintf('Number of nodes: 5\nx coordinate = 1.035\ny coordinate = -3.873\n')
else
S = fileread(filename);
end
S =
'Number of nodes: 5 x coordinate = 1.035 y coordinate = -3.873 '
newvalue = string(10*randn(1,1))
newvalue = "1.9462"
newS = regexprep(S, '(?<=x coordinate = )(-?[\d.]+)', newvalue)
newS =
'Number of nodes: 5 x coordinate = 1.9462 y coordinate = -3.873 '
[fid, msg] = fopen(outfilename, 'w');
if fid < 0; error('could not open output file "%s" because "%s"', outfilename, msg); end
fwrite(fid, newS);
fclose(fid)
ans = 0
dbtype(outfilename)
1 Number of nodes: 5 2 x coordinate = 1.9462 3 y coordinate = -3.873
  2 个评论
sajad mhmzd
sajad mhmzd 2021-10-1
I wrote my own code for replacing a Num in a string but there is a problem. in the second loop the number 12 replace with 132 insted of 13 and i've been confused.
F = 'bodyNameRefManager_1.setBodies(new NeoObjectVector(new Object[] {}));';
for i=12:13
str_e = sprintf('bodyNameRefManager_%0.0f',i);
new = regexprep(F,'bodyNameRefManager_(\w)', str_e)
F = new;
end

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Migrate GUIDE Apps 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by