Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove trailing and leading whitespace for user-provided input in a batch file?

I know how to do this when the variable is pre-defined. However, when asking for the user to enter in some kind of input, how do I trim leading and trailing whitespace? This is what I have so far:

@echo off  set /p input=: echo. The input is %input% before  ::trim left whitespace for /f "tokens=* delims= " %%a in ("%input%") do set input=%%a ::trim right whitespace (up to 100 spaces at the end) for /l %%a in (1,1,100) do if "!input:~-1!"==" " set input=!input:~0,-1!   echo. The input is %input% after  pause 
like image 547
OopOop Avatar asked Jun 08 '10 23:06

OopOop


People also ask

How do you get rid of leading and trailing white spaces?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

Which function is used to remove leading and trailing whitespace of a string?

strip(): returns a new string after removing any leading and trailing whitespaces including tabs (\t). rstrip(): returns a new string with trailing whitespace removed.

Which function used to remove all leading and trailing?

You can use the STRIP function to remove both the leading and trailing spaces from the character strings.

Which functions would you choose to use to remove leading and trailing white spaces from a given string in Python?

If you only want to remove leading or trailing whitespace use lstrip() or rstrip() respectively.


1 Answers

The solution below works very well for me.

Only 4 lines and works with most (all?) characters.


Solution:

:Trim SetLocal EnableDelayedExpansion set Params=%* for /f "tokens=1*" %%a in ("!Params!") do EndLocal & set %1=%%b exit /b 

Test:

@echo off  call :Test1 & call :Test2 & call :Test3 & exit /b  :Trim SetLocal EnableDelayedExpansion set Params=%* for /f "tokens=1*" %%a in ("!Params!") do EndLocal & set %1=%%b exit /b  :Test1 set Value=   a b c    set Expected=a b c call :Trim Actual %Value% if "%Expected%" == "%Actual%" (echo Test1 passed) else (echo Test1 failed) exit /b  :Test2 SetLocal EnableDelayedExpansion set Value=   a \ / : * ? " ' < > | ` ~ @ # $ [ ] & ( ) + - _ = z     set Expected=a \ / : * ? " ' < > | ` ~ @ # $ [ ] & ( ) + - _ = z call :Trim Actual !Value! if !Expected! == !Actual! (echo Test2 passed) else (echo Test2 failed) exit /b  :Test3 set /p Value="Enter string to trim: " %=% echo Before: [%Value%] call :Trim Value %Value% echo After : [%Value%] exit /b 
like image 146
skataben Avatar answered Oct 11 '22 13:10

skataben