I have %var1% and %var2%

var1="UserInput"
var2=file.log

If a user types %var1% as "file.txt", how can I (if possible) check only the three last characters (Or the file format if that's possible) to see if it matches %var2%'s three last characters or file format?

Another method that does the same thing is also welcome (But the user-input variable must be there)

up vote 7 down vote accepted

If you are going to check a fixed number of characters, then you should check the last 4, else "file.Log" will match "file.myLog".

But the best option is to get the actual extension, regardless the length:

@echo off
setlocal
set "var1=file.Log"
set "var2=file.myLog"

:: Option 1 using FOR loops
for %%A in ("%var1%") do for %%B in ("%var2%") do if "%%~xA"=="%%~xB" (
  echo Match
) else (
  echo No Match
)

: Option 2 using CALL parameters
call :matchExtension "%var1%" "%var2%" &&echo Match||echo No Match
exit /b

:matchExtension file1 fil2 --> returns 0 (success) if match, 1 (error) if no match
if "%~x1"=="%~x2" exit /b 0
exit /b 1

How do I check if the three last characters of a variable match another variable?

Use variable substring syntax to extract the last 3 characters of each variable.

Example batch file:

@echo off
setlocal
set /p var1="UserInput: "
set var1last3=%var1:~-3%
set var2=file.log
set var2last3=%var2:~-3%
if %var1last3% == %var2last3% (
  echo Match
  ) else (
  echo No Match
  )
endlocal

Further Reading

  • It doesn't affect your answer's functionality, but why have you set enabledelayedexpansion when you don't use any !var! expansions? – AFH Oct 21 at 17:58
  • @AFH Force of habit. I've removed it to avoid any confusion:) – DavidPostill Oct 21 at 19:17
  • While your code answers the question, it doesn't really solve the problem. Examples where it won't work correctly: list.txt vs listxt, stuff.docx vs stuff.ocx, file1.o vs file2.o. These are all valid extensions for actual file formats, only listxt is a made up extension-less file name. – gronostaj Oct 22 at 7:29

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.