首页 > 解决方案 > 对 dir 进行区分大小写输入的解决方法

问题描述

我在 Windows 10 (x64) 上使用 Octave 5.1.0。我正在解析一系列目录,在每个目录中查找 Excel 电子表格,文件名中包含“日志”。问题是这些文件是手工创建的,文件命名不一致:有时是“日志”,有时是“日志”,等等......

看起来作为输入传递给dir函数的字符串是区分大小写的,所以如果我没有正确的大小写,则dir返回一个空结构。目前,我正在使用以下解决方法,但我想知道是否有更好的方法来做到这一点(首先,我没有捕获所有可能的大写/小写组合):

logbook = dir('*LogBook.xls*');
if isempty(logbook)
  logbook = dir('*logbook.xls*');
  if isempty(logbook)
    logbook = dir('*Logbook.xls*');
    if isempty(logbook)
      logbook = dir('*logBook.xls*');
      if isempty(logbook)
        error(['Could not find logbook spreadsheet in ' dir_name '.'])
      end
    end
  end
end

标签: directoryoctavecase-sensitivecase-insensitive

解决方案


您需要获取文件名列表(通过readdirdirls),然后在该列表中搜索字符串。如果你使用readdir,它可以这样做:

[files, err, msg] = readdir ('.'); # read current directory
if (err != 0)
  error ("failed to readdir (error code %d): %s", msg);
endif
logbook_indices = find (cellfun (@any, regexpi (files, 'logbook'));
logbook_filenames = files(logbook_indices);

一个不太标准的方法可能是:

glob ('*[lL][oO][gG][bB][oO][kK]*')

推荐阅读