Batch subtraction with leading zero

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
SIMMS7400
Posts: 546
Joined: 07 Jan 2016 07:47

Batch subtraction with leading zero

#1 Post by SIMMS7400 » 09 Dec 2018 19:01

Hi Folks -

I am building a process that requires me to extract the year from a file name.

The file name is as follows:
hp_profitandloss_extract_FY08.csv
The year will always be the last string preceeding the .csv.

I need to extract the year and set it in a variable and also set another variable that is 1 less. I run into an issue with batch subtraction when there is a leading zero. Is there an eays way around this?

This is what I have and works fine, except when encountrring a leading zero:

SET "DATAFILENAME=%~1"
SET "ENDYEAR=%DATAFILENAME:~-6%"
SET "ENDYEAR=%ENDYEAR:~0,2%"
SET /A "STARTYEAR=%ENDYEAR%-1"

SET "STARTPOV=Sep-%STARTYEAR%" & SET "ENDPOV=Oct-%ENDYEAR%"

echo %STARTYEAR%
echo %ENDYEAR%
pause
Thanks!

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: Batch subtraction with leading zero

#2 Post by Squashman » 09 Dec 2018 21:18

Been covered dozens of times on the forum if you search.

Put a 1 in front of the number so that it become 108. Then subtract 1. Then substring the last two positions.

SIMMS7400
Posts: 546
Joined: 07 Jan 2016 07:47

Re: Batch subtraction with leading zero

#3 Post by SIMMS7400 » 10 Dec 2018 02:54

HI Squash -

Ah yes, very easy!

This solves for my issue, but looks awfully clunky.

Code: Select all

SET "ENDYEAR=%DATAFILENAME:~-6%"
SET "ENDYEAR=%ENDYEAR:~0,2%"
SET /A "STARTYEAR=1%ENDYEAR%-1"
SET "STARTYEAR=%STARTYEAR:~1,3%"
SET "STARTPOV=Sep-%STARTYEAR%" & SET "ENDPOV=Oct-%ENDYEAR%"

Post Reply