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

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

问题描述

我知道如何做到这一点当变量pre定义。然而,当要求为用户在某种输入的进入,我怎么修剪引导和拖尾的空白?这是我到目前为止有:

 关闭@echo集/ P输入=:
回声。输入是输入%之前%::修剪左侧空白
FOR / F令牌= * delims =%%一中(%输入%)并设置输入= %%一
::修剪右空白(高达100处所末)
对/ L %%一个在(1,1,100)做,如果输入:!〜-1!==设置输入=输入:〜0,-1!回声。输入是输入%后%暂停


解决方案

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

 关闭@echo
SETLOCAL enabledelayedexpansion
:胡说
集/ P输入=:
回音。%输入%
FOR / F令牌= * delims =%%一中(%输入%)并设置输入= %%一
对/ L %%一个在(1,1,100)做,如果输入:!〜-1!==设置输入=输入:〜0,-1!
回音。%输入%
暂停
转到嗒嗒

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天全站免登陆