Selecting middle of file name

2 ビュー (過去 30 日間)
Sia Sharma
Sia Sharma 2022 年 11 月 9 日
コメント済み: Voss 2022 年 11 月 10 日
Hi, I have many files with varying names. I have a string from 8:12 that is the same for all. However it is not the beginning of the file name. How would i write a statement to address all of them with the same numbers at spot 8:12?
I want to follow it up with an if statment so that MATLab can hunt my file names for the specific numbers in 8:12.
Thank you!

回答 (2 件)

Voss
Voss 2022 年 11 月 9 日
If your file names are stored as a cell array of character vectors:
fn = {'abcdefg89012mnopq' 'abcdefg89013mnopq' 'abcdefg89014mnopq' 'abcdefg89012mnopz'};
temp = cellfun(@(x)x(8:12),fn,'UniformOutput',false)
temp = 1×4 cell array
{'89012'} {'89013'} {'89014'} {'89012'}
Alternatively, if they are stored as a string array:
fn = ["abcdefg89012mnopq" "abcdefg89013mnopq" "abcdefg89014mnopq" "abcdefg89012mnopz"];
temp = extractBetween(fn,8,12)
temp = 1×4 string array
"89012" "89013" "89014" "89012"
Then, regardless of whether cell array or string array:
idx = strcmp(temp,'89012') % logical index of which names match '89012' in positions 8:12
idx = 1×4 logical array
1 0 0 1
fn(idx) % the matching file names
ans = 1×2 string array
"abcdefg89012mnopq" "abcdefg89012mnopz"
  2 件のコメント
Sia Sharma
Sia Sharma 2022 年 11 月 10 日
Thank you!
Voss
Voss 2022 年 11 月 10 日
You're welcome! If you have any questions, let me know. Otherwise, please "Accept this Answer". Thanks!

サインインしてコメントする。


Image Analyst
Image Analyst 2022 年 11 月 10 日
Try this:
filePattern = fullfile(pwd, '*.txt'); % Whatever it is.
fileList = dir(filePattern);
for k = 1 : numel(fileList)
% Get the file name.
thisName = fileList(k).name;
% Get the characters in indexes 8 to 12 into a substring.
str = thisName(8:12);
% Search that substring for particular number, or as poster says:
% "hunt my file names for the specific numbers"
% For example see if there is a 9 in the substring.
if contains(str, '9')
% String contains the number we're looking for
end
end
If this is not what you wanted to do then give me a list of some typical filenames, "the specific numbers in 8:12" that you're seeking, and what you expect as the output.

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by