function [output_file]=clean_files(input_dir,filename,ext4,find_str,replace_str,output_dir); % Searches a text file for the TARGET string find_str % Replaces it with replace_str, and writes the output file. % find_str = '---.---'; % replace_str = ''; % filename = 'testfile'; % ext4 = '.csv'; % ALGORITHM % Parse file by reading 1 line at a time, % see if that line has the offending string using STRFIND, else write it % If it does, remove it, then write the remainder. % NOTE: the offending string will be assumed to never be in the 1st % position, but may occur more than once otherwise. output_file = [filename,'C']; if ~exist([output_dir,output_file,ext4]) fid = fopen([input_dir,filename,ext4]); alldata = fscanf(fid,'%s'); ismatch = strfind(alldata,find_str); if isempty(ismatch) eval(['!cp ',input_dir,filename,ext4,' ',output_dir,output_file,ext4]); else fclose(fid); fid=fopen([input_dir,filename,ext4]); fid2 = fopen([output_dir,output_file,ext4],'w'); isendoffile=0; while isendoffile==0 OneLine = fgetl(fid); matches = strfind(OneLine, find_str); if ~isempty(matches) OneLine = remove_str(OneLine,find_str,replace_str,matches); fprintf(fid2,'%\n',OneLine); elseif length(OneLine)<2 isendoffile=1; else fprintf(fid2,'%s\n',OneLine); end end fclose(fid); fclose(fid2); end end