0

I want to write a simple batch script which checks if the input string has more than 5 chars.

Something like:

SET /P INPUT=Enter your string:
IF %INPUT% > 5 (
          ECHO %INPUT% has more than 5 chars
) ELSE (
          ECHO %INPUT% has less than 5 chars
)

How I can perform these kind of checks in .bat?

ams2705
  • 287
  • 2
  • 5
  • 17

3 Answers3

3

You can look whether there is a character following the fifth with a simple substring operation:

if defined INPUT if "%INPUT:~5,1%"=="" (
    echo five or less characters
) else (
    echo more than five characters
)

No need to figure out the length of the string if you don't need the actual number somewhere. Although jeb's approach to get the length is fairly clever (and exactly the same idea that is used here).

Joey
  • 344,408
  • 85
  • 689
  • 683
  • +1; But this fails if INPUT is undefined. It will erroneously report that it is more than 5 chars because `%input:~5,1%` will expand to `~5,1`.Best to also check `if defined INPUT...` – dbenham Oct 04 '12 at 16:56
  • Corrected; thanks :-). I definitely need to do more batch stuff again; I'm forgetting the basics. – Joey Oct 04 '12 at 16:59
1

I'm sure you already that getting a string length from input is not very straight forward in batch file script. An easy approach is to test whether the first 5 characters (or any x number of characters) of the input string is the same as the input string. For example:

SET /P INPUT=Enter your string:
IF [%INPUT%]==[%INPUT:~0,5%] (
      ECHO %INPUT% has more than 5 chars
) ELSE (
      ECHO %INPUT% has less than 5 chars
)

Admittedly, this will not work for every logic scenario you might need, but its fairly straight forward for a number scenarios. FYI, I added the [] characters to prevent empty string comparisons.

Hope that helps...

lrivera
  • 514
  • 3
  • 8
  • +1; But your answer suffers the same problem as Joey's original answer before his edit. If INPUT is not defined, then `%INPUT:~0,5%` will expand to `~0,5` and you will get the wrong answer. Ideally you should also check if INPUT is defined. – dbenham Oct 04 '12 at 17:43
0

This is pretty similar to this question. Sounds like you have to write your own function for that, then compare the result to 5. Luckily, the answerer to that question provided a function for you.

Also, Google is your friend.

Community
  • 1
  • 1
boztalay
  • 562
  • 6
  • 17