file name manipulation

I have a file name that takes the form: S_1_X_Y where X can be an integer between 1-16, and Y is a letter a,b,c,d.
I want to be able to just replace the number X by a user defined value.
any help greatly appreciated. Thanks

1 件のコメント

Jason
Jason 2011 年 5 月 6 日
Just to add, the "1" in the file name can also be 1,2,3,4.

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

 採用された回答

Oleg Komarov
Oleg Komarov 2011 年 5 月 6 日

0 投票

X = 1;
Y = 'a';
sprintf('S_1_%d_%s',X,Y)
EDIT
str = 'S_1_6_a'
x = 3;
regexprep(str,'(_)\d+(_[abcd])', ['$1' sprintf('%d',x) '$2'])
ans =
S_1_3_a

4 件のコメント

Jason
Jason 2011 年 5 月 6 日
Y is not a variable, its fixed by the first file I read in, and so would need to extract this from the file name
Oleg Komarov
Oleg Komarov 2011 年 5 月 6 日
I misread your request at first, now given a string name "str", it replaces the 6 in the example with the number 3.
Jason
Jason 2011 年 5 月 6 日
but sometimes the number to be replaced can be single digit 1-9) or double digit 10-16.
Jason
Jason 2011 年 5 月 6 日
sorry, i didn't realise you code handles this. Thanks

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

その他の回答 (1 件)

Teja Muppirala
Teja Muppirala 2011 年 5 月 6 日

0 投票

NUM2STR is useful for stuff like this.
Y = {'a' 'b' 'c' 'd'}
for jj = 1:4
for n = 1:9
filename = ['S_1_' num2str(n) '_' Y{jj}]
end
end
Or alternatively, if you need to have zeros in there like '001', '002', '003' then you can use SPRINTF instead of NUM2STR
n = 7;
filename = ['S_1_' sprintf('%03.f',n) '_a']
n = 61;
filename = ['S_1_' sprintf('%03.f',n) '_a']

3 件のコメント

Oleg Komarov
Oleg Komarov 2011 年 5 月 6 日
num2str supports the format:
num2str(1,'%03.f')
Jason
Jason 2011 年 5 月 6 日
sorry, I didn't explain my question clearly. I read in a filename that takes the form S_1_X_Y e.g. S_1_6_a the "a" character can be either a,b,c,d. X can be 1 to 16..
Once this filename is read in as a string, I need to keep it exactly the same, but only change the character X to a different number between 1-16.
Oleg Komarov
Oleg Komarov 2011 年 5 月 6 日
I edited my answer. Check it out.

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

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by