File Exchange Pick of the Week

Our best user submissions

Determining next available file name

Jiro‘s Pick this week is nextname by Stephen Cobeldick.

Stephen is no stranger in the MATLAB user community arena. As of the writing of this post, Stephen ranks 44 out of over 15,000 File Exchange users. He also ranks 5 out of over 190,000 MATLAB Answers users. One of his files have been Picked not once, not twice, but three times in the past. It just goes to show how well-written his piece of code is.

This submission is something that I have needed to do numerous times in the past, which is creating unique, incrementing file name.

Let’s say that there are three files in the current folder: “A001.txt”, “A002.txt”, “A003.txt”. I want to determine the next file name to use. In this case, the file name will be “A004.txt”. And let’s say that I need to do this type of operation repeatedly. Of course, I can keep track of the file names, and increment accordingly. Instead, I would like to automatically determine the next possible file name, since the current folder may contain some files from previous runs.

With nextname, you specify the file name structure, including the number to start incrementing. It will automatically start counting up until it finds a file name that is not being used.

dir A*.txt
A001.txt  A002.txt  A003.txt  

newname = nextname('A','001','.txt')
newname =
    'A004.txt'

The numbers could be in different formats, and you can have special characters.

dir B*.txt
B_01.txt  B_02.txt  B_05.txt  

newname = nextname('B','_01','.txt')
newname =
    'B_03.txt'

Stephen includes an example with the File Exchange entry, and the function has well-written help. The code is elegently written, with use of regular expressions.

Comments

Give it a try and let us know what you think here or leave a comment for Stephen.




Published with MATLAB® R2019b

|
  • print

コメント

コメントを残すには、ここ をクリックして MathWorks アカウントにサインインするか新しい MathWorks アカウントを作成します。