如何删除批处理文件中用户提供的输入的尾随和前导空格? [英] How to remove trailing and leading whitespace for user-provided input in a batch file?

查看:32
本文介绍了如何删除批处理文件中用户提供的输入的尾随和前导空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在预定义变量时执行此操作.但是,当要求用户输入某种输入时,如何修剪前导和尾随空格?这是我目前所拥有的:

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

推荐答案

您需要启用延迟扩展.试试这个:

You need to enable delayed expansion. Try this:

@echo off
setlocal enabledelayedexpansion
:blah
set /p input=:
echo."%input%"
for /f "tokens=* delims= " %%a in ("%input%") do set input=%%a
for /l %%a in (1,1,100) do if "!input:~-1!"==" " set input=!input:~0,-1!
echo."%input%"
pause
goto blah

这篇关于如何删除批处理文件中用户提供的输入的尾随和前导空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆