在您的问题中,不清楚输入文件是否可以包含没有“LENGTH=(”字符串的行。
我认为可以。
根据您指定的输入文件行的格式,您可以:
- 使用
findstr 检查是否存在“LENGTH=(”字符串
- 在行中找到要替换的号码的位置,再次使用
findstr
- 将字符串的一部分替换为“d”数组中的数字,将其转换为字符串
这个方法已经在下面的代码中实现了;还添加了对“d”数组中值的数量与要修改的行数的检查。
我使用了一个输入文件,其中包含没有“LENGTH=(”字符串的行;在这种情况下,原始字符串被写入 OUTPUT 文件中。
输入文件
NODE LABEL="NODE-1", LENGTH=(0.001,0.69, 1.805, 5, 10, \
NODE LABEL="NODE-2", LENGTH=(0.005,0.69, 1.805, 5, 10, \
NODE LABEL="NODE-3", WIDTH=(0.005,0.69, 1.805, 5, 10, \
NODE LABEL="NODE-4", XXXX=(0.005,0.69, 1.805, 5, 10, \
NODE LABEL="NODE-5", YYYYYYYY=(0.067,0.69, 1.805, 5, 10, \
NODE LABEL="NODE-6", LENGTH=(0.005,0.69, 1.805, 5, 10, \
脚本
% Define the array with replacing values
d =[0.010
0.120
0.140];
% Get the number of possible replaceable input file strings
n_val=length(d);
% Open INPUT and OUTPUT files
fp_in=fopen('in_file.txt','rt')
fp_out=fopen('out_file.txt','wt')
% Initialize counter
cnt=1;
% Read the input file line by line
while(1)
tline = fgetl(fp_in)
if(ischar(tline))
% If current input line contains the "LENGTH=(" string, try to
% replace the number
if(findstr(tline,'LENGTH=('))
% If "d" array does not contains enough values, generate error
% message
if(cnt > n_val)
error('Not enough values in "d" array')
end
% Replace the number in the string with a value from "d" array
b=findstr(tline,'(')
c=findstr(tline,',')
tline(b+1:c(2)-1)=sprintf('%4.3f',d(cnt))
% Print the modified line in the OUTPUT file
fprintf(fp_out,'%s\n',tline)
% Increment the counter
cnt=cnt+1
else
% If the current line does not contains the "LENGTH=(" string,
% writhe the line in the OUTPUT file as it is
fprintf(fp_out,'%s\n',tline)
end
else
% Stop reading INPUT file
break
end
end
% Close INPUT and OUTPUT files
fclose(fp_in);
fclose(fp_out);
输出文件
NODE LABEL="NODE-1", LENGTH=(0.010,0.69, 1.805, 5, 10, \
NODE LABEL="NODE-2", LENGTH=(0.120,0.69, 1.805, 5, 10, \
NODE LABEL="NODE-3", WIDTH=(0.005,0.69, 1.805, 5, 10, \
NODE LABEL="NODE-4", XXXX=(0.005,0.69, 1.805, 5, 10, \
NODE LABEL="NODE-5", YYYYYYYY=(0.067,0.69, 1.805, 5, 10, \
NODE LABEL="NODE-6", LENGTH=(0.140,0.69, 1.805, 5, 10, \
希望这会有所帮助。