1.

Solve : substring indexing?

Answer»

I try to INSERT a SEQUENCE number into a file name

to file name = from file name without extension + file sequence + from file name extension

e.g.
Personal Folders.pst will become Personal Folders 2.pst

please see the code I wrote below. Is there a WAY to simplify? I tried replacing the substring index by a counter %m% i.e. %fromfile1:~%m%,1% but it did not work.

Any suggestion will be appreciated! thanks.

set tofile1=%fromfile1% %filesequence%

if not %fromfile1:~-1,1% == . goto next1
set tofile1=%fromfile1:~0,-1% %filesequence%%fromfile1:~-1%
:next1

if not %fromfile1:~-2,1% == . goto next2
set tofile1=%fromfile1:~0,-2% %filesequence%%fromfile1:~-2%
:next2

if not %fromfile1:~-3,1% == . goto next3
set tofile1=%fromfile1:~0,-3% %filesequence%%fromfile1:~-3%
:next3

if not %fromfile1:~-4,1% == . goto next4
set tofile1=%fromfile1:~0,-4% %filesequence%%fromfile1:~-4%
:next4

The simplest way to manipulate filenames is to use FOR. There are a number of "variable modifiers". See the FOR documentation.

Example (try it in a batch script)

FOR %%A in ("Personal Folders.pst") do @echo %%~nA 2%%~xA



Quote

I tried replacing the substring index by a counter %m% i.e. %fromfile1:~%m%,1% but it did not work.

You can do this if you use CALL to expand the "count" variable. You have to add an extra percent sign at start and FINISH of the string expression. I have underlined and coloured them blue here...

@echo off
set /p MyString="String? "
set num=0
:Loop
call set char=%%MyString:~%num%,1%%
if "%char%"=="" goto ExitLoop
set /a Cpos=%num%+1
echo Character %Cpos%: "%char%"
set /a num=%num%+1
goto Loop
:ExitLoop
echo Reached end of string
pause


String? Not in civilised countries.
Character 1: "N"
Character 2: "o"
Character 3: "t"
Character 4: " "
Character 5: "i"
Character 6: "n"
Character 7: " "
Character 8: "c"
Character 9: "i"
Character 10: "v"
Character 11: "i"
Character 12: "l"
Character 13: "i"
Character 14: "s"
Character 15: "e"
Character 16: "d"
Character 17: " "
Character 18: "c"
Character 19: "o"
Character 20: "u"
Character 21: "n"
Character 22: "t"
Character 23: "r"
Character 24: "i"
Character 25: "e"
Character 26: "s"
Character 27: "."
Reached end of string
Press any key to continue . . .



Use CALL to simulate arrays

@echo off
setlocal enabledelayedexpansion

echo Abacus>test.txt
echo Bear>>test.txt
echo Codifier>>test.txt
echo David>>test.txt

set n=0
for /f "delims=" %%A in (test.txt) do (
call set array!!n!!=%%A
set /a n+=1
)
set a | find "array"



array0=Abacus
array1=Bear
array2=Codifier
array3=David

Thanks very much for the information. You amazed me of what it can do.


Discussion

No Comment Found