Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

dir() function not working?

Asked by John on 19 Mar 2012

Hello,

I'm trying to rename some files using the code below. It works if I list the file names at the beginning but there are many files in the folder so I wanted to use the dir()function but it won't work for some reason. Would anybody know why?

Thanks

Working code:

files = {'RW.a_process',...
'Copy of RW.a_process',...
'Copy (2) of RW.a_process',...
'Copy (1000) of RW.a_process'}
for k = 1 : length(files)
	oldFileName = files{k}
	leftParenthesisLocation = strfind(oldFileName, 'Copy (');
	if leftParenthesisLocation >= 1
		% Handle cases of Copy (nnn) of RW.a_process
		rightParenthesisLocation = strfind(oldFileName(leftParenthesisLocation:end), ')');
		if rightParenthesisLocation > 1
			strNumber = oldFileName(leftParenthesisLocation+6:rightParenthesisLocation-1)
			% Get name to the right of the right parenthesis.
			newFileName = oldFileName(rightParenthesisLocation+5:end);
			[folder, baseFileName, ext] = fileparts(newFileName);
			newFileName = sprintf('%s%s%s', baseFileName, strNumber, ext);
			fprintf('New Filename = %s\n', newFileName); % Print blank line.
		end

Not working code:

files = dir('*.a_process');
for k = 1 : length(files)
	oldFileName = files{k}
	leftParenthesisLocation = strfind(oldFileName, 'Copy (');
	if leftParenthesisLocation >= 1
		% Handle cases of Copy (nnn) of RW.a_cycle
		rightParenthesisLocation = strfind(oldFileName(leftParenthesisLocation:end), ')');
		if rightParenthesisLocation > 1
			strNumber = oldFileName(leftParenthesisLocation+6:rightParenthesisLocation-1)
			% Get name to the right of the right parenthesis.
			newFileName = oldFileName(rightParenthesisLocation+5:end);
			[folder, baseFileName, ext] = fileparts(newFileName);
			newFileName = sprintf('%s%s%s', baseFileName, strNumber, ext);
			fprintf('New Filename = %s\n', newFileName); % Print blank line.
             movefile(oldFileName, newFileName) 
		end 

0 Comments

John

Tags

Products

No products are associated with this question.

1 Answer

Answer by Honglei Chen on 19 Mar 2012
Accepted answer

You need to use

oldFileName = files(k).name

see

http://www.mathworks.com/help/techdoc/ref/dir.html

0 Comments

Honglei Chen

Contact us