How do I name a file from part of the file name read in?

조회 수: 11 (최근 30일)
Christopher
Christopher 2014년 1월 27일
답변: Image Analyst 2014년 1월 27일
I would like to read in files from a directory, store their names, modify the files, and write out new files with a name based on the files read in. I have a solution that takes the first 8 characters of the read in file and uses that as part of the new written file. But, I would like the code to take the part of the name before a specific character is observed (an underscore "_") because the number of characters changes depending on the samples I'm analyzing. The file I read in is named "6145abc_acquired.txt" and I would like to name the written file "6145abc-ave100raw.txt".
Here's part of my current code:
files = dir('*.txt');
numfiles = numel(files);
for i=1:length(files)
filename = files(i).name;
[~,name] = fileparts(filename);
nameaves = name(1:8);
... in here I process the data creating the variable ave100...
dlmwrite([nameaves, '-ave100raw' '.txt'], ave100, '\t');
end
I would like to modify the name(1:8) to something that's more flexible and includes only what comes before the underscore "_".
Thanks.

채택된 답변

AJ von Alt
AJ von Alt 2014년 1월 27일
The function strsplit will split a string into parts based on a delimiter.
Replace
nameaves = name(1:8);
With:
namesplit = strsplit( name , '_' );
nameaves = namesplit{1};

추가 답변 (1개)

Image Analyst
Image Analyst 2014년 1월 27일
Try this:
filename = '6145abc_acquired.txt'
underlineIndex = find(filename == '_', 1, 'first')
newFileName = sprintf('%s-ave100raw.txt', filename(1:underlineIndex-1))

카테고리

Help CenterFile Exchange에서 Data Import and Analysis에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by