-1

How can I loop over the files with a particular pattern of filename in the current directory in Octave?

I found glob to be the best option to get a list of files in the current directory and you can use a 'pattern' to get a list of files of a particular pattern. Now I have a list of files which varies over two single integers in the name, such as

A-B123-1-c1, A-B123-1-c2, A-B123-2-c1, A-B123-2-c2.... and so on.

Now I want to loop over the digit between hyphens. I can use the loop variable in the pattern because the digit is sequential, but I can't figure out how to use the variable value within the pattern in glob.

I have used the following code to import filenames with a particular pattern:

filenames = glob("A-B123-*")

However, this code imports all the file names with the pattern A-B123- at once. I am trying to use the following loop:

for j = 1:8
filenames = glob("A-B123-%j-*")

But it outputs an empty cell:

filenames = {}(0x0)

I want the following output when the value of j is 1:

filenames =  

[1,1] = A-B123-1-c1

[2,1] = A-B123-1-c2

Can anyone suggest a solution?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • 2
    One of many possible duplicates: [Matlab file name with zero-padded numbers](https://stackoverflow.com/questions/14213442/matlab-file-name-with-zero-padded-numbers) – Cris Luengo May 26 '19 at 16:19

1 Answers1

0

Found the solution:

The 'sprintf' command can be used to pass a pattern to a string. We can use it to input pattern to the glob command:

for j = 1:8
filenames = glob(sprintf("A-B123-%d-*",j))

This loop goes through A-B123-1-* to A-B123-8-*

Another loop can be created within this loop for the * part to walk through c1,c2...