|
On Jun 1, 9:41 am, "dhuan Du" <dupe...@gmail.com> wrote:
> TideMan <mul...@gmail.com> wrote in message <266e246b-6736-4005-8a7c-f2a568434...@v11g2000prk.googlegroups.com>...
> > On Jun 1, 9:04 am, "dhuan Du" <dupe...@gmail.com> wrote:
> > > Hi friends:
>
> > > I would like to find and replace the string "t0=1" with the string "t0=2" in a text file. I have tried replaceinfile.m, but it does not work. It looks there are problem in perl stuff.
> > > msg= Can't open: Invalid argument.
>
> > > I do not know how to use perl. I wonder if there are any methods only using matlab to solve my issue?
>
> > > Thanks,
>
> > > Lili
>
> > I'm not familiar with replaceinfile, but it's more likely you've
> > screwed up using it than that there is a problem with perl.
> > Here's a perl script that you can execute from a DOS prompt:
> > perl -p -e "s/t0=1/t0=2/g" infile.txt > outfile.txt
>
> Hi,
>
> thanks a lot for your suggestions. I do not know how to use the script in my matlab code. I would like you take a look at my codes.
>
> My code is given below:
> fid = fopen('t.txt');
> tline = fgetl(fid);
> while ischar(tline)
> position=strfind(tline, ',"1") =');
> if position>=0
> position=length(',"1") =')+position+1;
> old_data=tline(position:(length(tline)-1))
> new_data=num2str(str2num(old_data)*1.2);
> [s, message]=replaceinfile(old_data,new_data,'t.txt');
> end
> tline = fgetl(fid);
> end
> fclose(fid);
>
> ++++++++++++++++++++++
>
> This is the two line perl codes used in replaceinfile.m.
>
> perlCmd = sprintf('"%s"',fullfile(matlabroot, 'sys\perl\win32\bin\perl'));
> perlstr = sprintf('%s -i.bak -pe"s/%s/%s/g" "%s"', perlCmd, str1, str2,infile);
>
> [s,msg] = dos(perlstr);
>
> +++++++++++++++++++"error message "+++++++++++++++++
> for example I give the infile name 't.txt', I always get the msg='cannot do inplace edit on t.txt': file exists.
>
> +++++++++++++++++++++++++++++++++++++++++++++++++++++
> t.txt file looks like
> t0("1","1") = 1;
> t0("1","2") = 1.9;
> t0("2","4") = 1.667;
> t0("3","4") = 1.1;
> t0("4","4") = 1.333;
> t0("5","1") = 8.333;
> t0("5","2") = 11.667;
> t0("6","1") = 0.667;
> t0("6","2") = 0.833;
> t0("6","3") = 0.5;
> t0("7","1") = 0.583;
>
> Thanks a lot!
Well, I wouldn't do it this way at all.
Here's how I'd do it:
fid = fopen('t.txt','rt');
a=fscanf(fid,'%c'); % Read in the whole file
fclose(fid);
a=strrep(a,str1,str2); % Replace strings
a=strrep(a,str3,str4);
etc
etc
fid = fopen('t1.txt','wt');
fprintf(fid,'%c',a); % Write out the whole file
fclose(fid);
|