39

変数が事前定義されている場合、これを行う方法を知っています。ただし、ユーザーにある種の入力の入力を求める場合、先頭と末尾の空白を削除するにはどうすればよいですか?これは私がこれまでに持っているものです:

@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
4

17 に答える 17

31

以下の解決策は私にとって非常にうまく機能します。

たった4行で、ほとんど(すべて?)の文字で機能します。


解決:

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

テスト:

@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
于 2014-09-27T23:01:07.240 に答える
27

遅延拡張を有効にする必要があります。これを試して:

@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
于 2010-06-08T23:52:55.430 に答える
16

私が使用している非常に短くて簡単な解決策はこれです:

@ECHO OFF

SET /p NAME=- NAME ? 
ECHO "%NAME%"
CALL :TRIM %NAME% NAME
ECHO "%NAME%"
PAUSE

:TRIM
SET %2=%1
GOTO :EOF

結果:

- NAME ?  my_name
" my_name "
"my_name"
于 2012-08-23T09:53:35.540 に答える
11

関数への参照による呼び出し(はい、「バッチ」にもポインターがあります!)と「サブ関数」を使用したコンパクトなソリューションを提示したいと思います。

  @ECHO OFF
  SETLOCAL ENABLEDELAYEDEXPANSION

  SET /p NAME=- NAME ? 
  ECHO "%NAME%"
  CALL :TRIM NAME
  ECHO "%NAME%"
  GOTO :EOF

  :TRIM
  SetLocal EnableDelayedExpansion
  Call :TRIMSUB %%%1%%
  EndLocal & set %1=%tempvar%
  GOTO :EOF

  :TRIMSUB
  set tempvar=%*
  GOTO :EOF
于 2013-10-30T15:25:57.460 に答える
4

Forumpieの回答を改善するための秘訣は%*、サブで(すべてのパラメーター)を使用することです。

編集:より多くの洞察を提供するために、TRIMサブルーチンパラメータのエコーを追加しました

@ECHO OFF

SET /p NAME=- NAME ? 
ECHO "%NAME%"
CALL :TRIM %NAME%
SET NAME=%TRIMRESULT%
ECHO "%NAME%"

GOTO :EOF

:TRIM
  echo "%1"
  echo "%2"
  echo "%3"
  echo "%4"
  SET TRIMRESULT=%*
GOTO :EOF

これにより、先頭と末尾のスペースが削除されますが、その間にすべてのスペースが保持されます。

"  1 2    3 4    "
"1 2    3 4"

%*の詳細:バッチパラメータ

于 2015-08-19T00:52:38.863 に答える
1

また、空白をパラメーターとして持つ変数をサブに渡して、サブ内で渡されたパラメーターを使用してそれらを再度設定することにより、空白を取り除くこともできます。

@echo off 
set "a=    apple      "
set "b=     banana    "
echo [%a%]
echo [%b%]
call :Strip %a% %b%
pause
goto :EOF

:Strip
set a=%1
set b=%2
echo [%a%]
echo [%b%]

----------------
Results....
[    apple      ]
[     banana    ]
[apple]
[banana]
Press any key to continue . . .
于 2014-07-03T18:12:21.867 に答える
1

以下の:trimAllサブルーチン:

  • 渡された文字列から先頭と末尾のタブとスペースを削除します
  • 遅延拡張を無効または有効にして安全に呼び出すことができます
  • 毒のキャラクターを処理します(例!、、、、%など^
  • CRとLFはサポートされていません

参考文献や情報についてはコメントを読んでください。

@echo off & setLocal enableExtensions disableDelayedExpansion
:: https://www.dostips.com/forum/viewtopic.php?t=4308
(call;) %= sets errorLevel to 0 =%
(set lf=^
%= BLANK LINE REQUIRED =%
)
:: kudos to Carlos for superior method of capturing CR
:: https://www.dostips.com/forum/viewtopic.php?p=40757#p40757
set "cr=" & if not defined cr for /f "skip=1" %%C in (
    'echo(^|replace ? . /w /u'
) do set "cr=%%C"

set ^"orig=  !random!  !  ^^!  ^^^^!  ^"^^  ^&^"^&  ^^^" %%os%%  ^"

call :trimAll res1 orig
setLocal enableDelayedExpansion
call :trimAll res2 orig
echo(orig: [!orig!]
echo(res1: [!res1!]
echo(res2: [!res2!]
endLocal

endLocal & goto :EOF

:trimAll result= original=
:: trims leading and trailing whitespace from a string
:: special thanks to Jeb for
:: https://stackoverflow.com/a/8257951
setLocal
set "ddx=!" %= is delayed expansion enabled or disabled? =%
setLocal enableDelayedExpansion
set "die=" & if not defined %2 (
    >&2 echo(  ERROR: var "%2" not defined & set "die=1"
) else set "str=!%2!" %= if =%

if not defined die for %%L in ("!lf!") ^
do if "!str!" neq "!str:%%~L=!" (
    >&2 echo(  ERROR: var "%2" contains linefeeds & set "die=1"
) %= if =%

if not defined die for %%C in ("!cr!") ^
do if "!str!" neq "!str:%%~C=!" (
    >&2 echo(  ERROR: var "%2" contains carriage returns
    set "die=1"
) %= if =%

if defined die goto die

(for /f eol^= %%A in ("!str!") do rem nop
) || (
    >&2 echo(WARNING: var "%2" consists entirely of whitespace
    endLocal & endLocal & set "%1=" & exit /b 0
) %= cond exec =%

:: prepare string for trimming...
:: double carets
set "str=!str:^=^^^^!"
:: double quotes
set "str=!str:"=""!"
:: escape exclaims
set "str=%str:!=^^^!%" !

:: act of CALLing subfunction with
:: expanded string trims trailing whitespace
call :_trimAll "%%str%%

:: prepare string to be passed over endLocal boundary...
:: double carets again if delayed expansion enabled
if not defined ddx set "str=!str:^=^^^^!"
:: escape exclaims again if delayed expansion enabled
if not defined ddx set "str=%str:!=^^^!%" !
:: restore quotes
set "str=!str:""="!"

:: pass string over endLocal boundary and trim leading whitespace
for /f tokens^=*^ eol^= %%a in ("!str!") do (
    endLocal & endLocal & set "%1=%%a" !
) %= for /f =%
exit /b 0

:die
endLocal & endLocal & set "%1=" & exit /b 1

:_trimAll
:: subfunction
:: trailing exclaim is required as explained by Jeb at
:: https://www.dostips.com/forum/viewtopic.php?p=6933#p6933
set "str=%~1" !
exit /b 0

HTHとHNY!;)

于 2018-01-01T15:25:48.067 に答える
1

ちょうどこれを思いついた:

set sString=" hello|123(4) "
call :trimMENew %sString%
echo "%sString%"
exit /b 0

:trimMeNew
set "sString=%~1"
if "%sString:~0,1%" == " " set "sString=%sString:~1%"
if "%sString:~-1%" == " " set "sString=%sString:~0,-1%"
exit /b 0
于 2020-07-16T19:31:37.807 に答える
1

ここで紹介したすべてのソリューションは、私にとって十分に完全ではなく、いずれかの場合に機能しないことがわかりました。

注意

スタックオーバーフローは、コピーして貼り付けたコードで集計文字を誤って処理する(およびのような他の文字を失う\x01)ようです。そのため、CTRL + Cで直接コピーすると、以下のコードが機能しない可能性があります。スクリプトを直接ダウンロードするには、最後にあるリンクを使用してください。

Trim_var.bat

@echo off

rem drop the output variable value
if not "%~2" == "" if not "%~1" == "%~2" set "%~2="

if not defined %~1 exit /b 0

setlocal DISABLEDELAYEDEXPANSION

rem Load and replace a value quote characters by the \x01 character.
call set "RETURN_VALUE=%%%~1:"=%%"

:TRIM_LEFT_LOOP
if not defined RETURN_VALUE exit /b 0
if not ^%RETURN_VALUE:~0,1%/ == ^ / if not ^%RETURN_VALUE:~0,1%/ == ^   / goto TRIM_RIGHT_LOOP
set "RETURN_VALUE=%RETURN_VALUE:~1%"
if not defined RETURN_VALUE exit /b 0
goto TRIM_LEFT_LOOP

:TRIM_RIGHT_LOOP
if not defined RETURN_VALUE exit /b 0
if not ^%RETURN_VALUE:~-1%/ == ^ / if not ^%RETURN_VALUE:~-1%/ == ^ / goto TRIM_RIGHT_LOOP_END
set "RETURN_VALUE=%RETURN_VALUE:~0,-1%"
goto TRIM_RIGHT_LOOP

:TRIM_RIGHT_LOOP_END
rem recode quote and exclamation characters
set "__ESC__=^"
set __QUOT__=^"
set "__EXCL__=!"
set "RETURN_VALUE=%RETURN_VALUE:!=!__EXCL__!%"
set "RETURN_VALUE=%RETURN_VALUE:^=!__ESC__!%"
set "RETURN_VALUE=%RETURN_VALUE:=!__QUOT__!%"

rem safe set
setlocal ENABLEDELAYEDEXPANSION
for /F "tokens=* delims=" %%i in ("!RETURN_VALUE!") do for /F "tokens=* delims=" %%j in ("%%i") do (
  endlocal
  endlocal
  if not "%~2" == "" (
    set "%~2=%%j"
  ) else (
    set "%~1=%%j"
  )
)

exit /b 0

echo_var.bat

@echo off

if not defined %~1 (
  echo.%~2%~3
  exit /b 0
)

setlocal DISABLEDELAYEDEXPANSION

rem Load and replace a value quote characters by the \x01 character.
call set "RETURN_VALUE=%%%~1:"=%%"

rem recode quote and exclamation characters
set "__ESC__=^"
set __QUOT__=^"
set "__EXCL__=!"
set "RETURN_VALUE=%RETURN_VALUE:!=!__EXCL__!%"
set "RETURN_VALUE=%RETURN_VALUE:^=!__ESC__!%"
set "RETURN_VALUE=%RETURN_VALUE:=!__QUOT__!%"

rem safe echo
setlocal ENABLEDELAYEDEXPANSION
for /F "tokens=* delims=" %%i in ("!RETURN_VALUE!") do for /F "tokens=* delims=" %%j in ("%%i") do (
  endlocal
  endlocal
  echo.%~2%%j%~3
)

exit /b 0

test_trim_var.bat

@echo off

setlocal DISABLEDELAYEDEXPANSION

set myvar1=              1 ! 2 ^| 3 ^& 4 ^^ 5 = 6 , 7 ; 8 * 9 # 0 %% 1 / 2 \ 3 ? 4 ^> 5 ^< 6 " 7             

call "trim_var.bat" myvar1 myvar2

call "echo_var.bat" myvar1 - -
call "echo_var.bat" myvar2 - -

出力

-                        1 ! 2 | 3 & 4 ^ 5 = 6 , 7 ; 8 * 9 # 0 % 1 / 2 \ 3 ? 4 > 5 < 6 " 7               -
-1 ! 2 | 3 & 4 ^ 5 = 6 , 7 ; 8 * 9 # 0 % 1 / 2 \ 3 ? 4 > 5 < 6 " 7-

最新の実装:https ://sourceforge.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/std/trim_var.bat

長所

  • 、、、など!のほぼすべての特定の文字を安全に処理します。%^"

短所

  • 文字は文字に"置き換えられ、\x01現在のコードページの影響を受ける可能性があります(テストされていません)。
于 2020-07-18T22:04:24.050 に答える
1

これは私の手っ取り早い解決策でした。入力テキストにファイル名で禁止されている文字が含まれていると、予期しない結果が生じることに注意してください。

@echo off
set /p input=Enter some text with spaces before and after^>
echo "%input%"
for /f "tokens=*" %%i in ('echo %input%') do set trimmed=%%~nxi
echo "%trimmed%"

編集

より堅牢なテキスト入力文字セットを提供し、それでもfor in('echo ...')アプローチによって通常残される単一の末尾スペースを削除するには、これは代替手段です。

set /p input=Enter some text with spaces before and after^>
for /f "tokens=*" %%i in ('echo %input%') do set j=%%i
set trimmed=%j:~0,-1%
echo "%trimmed%"
于 2021-02-02T10:14:37.613 に答える
0

私はこのようにしました(一時的に遅延拡張をオンにします):

      ...
sqlcmd -b -S %COMPUTERNAME% -E -d %DBNAME% -Q "SELECT label from document WHERE label = '%DOCID%';" -h-1 -o Result.txt
      if errorlevel 1 goto INVALID
    :: Read SQL result and trim trailing whitespace
    SET /P ITEM=<Result.txt
    @echo ITEM is %ITEM%.
    setlocal enabledelayedexpansion
    for /l %%a in (1,1,100) do if "!ITEM:~-1!"==" " set ITEM=!ITEM:~0,-1!
    setlocal disabledelayedexpansion
    @echo Var ITEM=%ITEM% now has trailing spaces trimmed.
....
于 2011-03-02T22:48:32.987 に答える
0
  @echo off & setlocal enableextensions
  rem enabledelayedexpansion
  set S=  This  is  a  test
  echo %S%.
  for /f "tokens=* delims= " %%a in ('echo %S%') do set S=%%a
  echo %S%.
  endlocal & goto :EOF

http://www.netikka.net/tsneti/info/tscmd079.htmから

先頭のスペースを削除します。

于 2010-06-08T23:15:58.457 に答える
0
@echo off
setlocal EnableDelayedExpansion
set S=  This  is  a  test
echo %S%.
for /f "tokens=* delims= " %%a in ('echo %S%') do (set b=%%a & set b=!b: =! & echo !b!)
endlocal & goto :EOF

また

@echo off
setlocal EnableDelayedExpansion
set S=  This  is  a  test
echo %S%.
for /f "tokens=* delims= " %%a in ('echo %S%') do (set b=%%a & set b=!b: =_! & echo !b!)
endlocal & goto :EOF
于 2013-06-24T00:05:38.130 に答える
0
for /f "usebackq tokens=*" %%a in (`echo %StringWithLeadingSpaces%`) do set StringWithout=%%a

これは非常に簡単です。forパラメータがない場合、スペースは区切り文字と見なされます。パラメータとして「*」を設定tokensすると、プログラムはスペースではない文字列のすべての部分を収集し、それらを新しい文字列に配置して、独自のギャップを挿入します。

于 2019-01-04T14:09:17.113 に答える
0

関数を作成する必要がありました。

次のように使用します。

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION


set "TextString=    Purple Cows are flying in the Air Tonight         "
echo REM ^^Notice there is whitespace at the start and end of the TextString
echo "!TextString!"
CALL:trimWhiteSpace "!TextString!" OutPutString
echo Resulting Trimmed Text: "!OutPutString!"
echo REM ^^Now there should be no White space at the start or end.

Exit /B

これをバッチファイルの最後に追加します。

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B


::TRIM FUNCTIONS AREA::
:: USAGE:
:: trimWhiteSpace "!InputText!" OutputText
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: trimWhiteSpace "!InputText!" !OutputText!
:: ^^Because it has a ! around the OutPutText
:: Make Sure to add " around the InputText when running the call.
:: If you don't add the " then it will only accept the first word before a space.
::Example:
::  set "TextString=    Purple Cows are flying in the Air Tonight         "
::  echo REM ^^Notice there is whitespace at the start and end of the TextString
::  echo "!TextString!"
::  CALL:trimWhiteSpace "!TextString!" OutPutString
::  echo Resulting Trimmed Text: "!OutPutString!"
::  echo REM ^^Now there should be no White space at the start or end.

:trimWhiteSpace
set textToTrim=%~1
CALL:trimWhiteSpaceOnTheRight "!textToTrim!" OutPutString
SET textToTrim=!OutPutString!
CALL:trimWhiteSpaceOnTheLeft "!textToTrim!" OutPutString
SET %2=!OutPutString!
GOTO:EOF

:trimWhiteSpaceOnTheRight
set str=%~1
for /l %%a in (1,1,31) do if "!str:~-1!"==" " set str=!str:~0,-1!
SET %2=%str%
GOTO:EOF

:trimWhiteSpaceOnTheLeft
set str=%~1
for /f "tokens=* delims= " %%a in ("%str%") do set str=%%a
SET %2=%str%
GOTO:EOF

また、バッチファイルの先頭に「SETLOCALENABLEDELAYEDEXPANSION」を追加する必要があることを忘れないでください。そうしないと、これが正しく機能しません。

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.
于 2020-06-25T01:10:05.547 に答える
-2

newVarNoSpaces =%someVarWithSpacesを設定します:=%

于 2017-09-01T21:25:49.077 に答える
-3

ありがとう@ブラッドリーマウントフォード

「Show-Grp-of-UID.CMD」で正確に機能する「TrimRightWhitespace」を使用しています。:)改善のための他のアイデアは大歓迎です..^_ ^

于 2013-09-10T06:03:05.540 に答える