13

Windows バッチ ファイル内に次の文字列があります。

"-String"

文字列には、上に書かれているように、文字列の最初と最後に 2 つの引用符も含まれています。

最初と最後の文字を削除して、次の文字列を取得します。

-String

私はこれを試しました:

set currentParameter="-String"
echo %currentParameter:~1,-1%

これにより、文字列が次のように出力されます。

-String

しかし、編集した文字列を次のように保存しようとすると、失敗します。

set currentParameter="-String"
set currentParameter=%currentParameter:~1,-1%
echo %currentParameter%

何も印刷されません。私は何を間違っていますか?


これは本当に奇妙です。このような文字を削除すると機能します:

set currentParameter="-String"
set currentParameter=%currentParameter:~1,-1%
echo %currentParameter%

それは出力します:

-String

しかし、実際には私のバッチはもう少し複雑で、うまくいきません。私がプログラムしたものを示します:

@echo off

set string="-String","-String2"

Set count=0
For %%j in (%string%) Do Set /A count+=1


FOR /L %%H IN (1,1,%COUNT%) DO ( 

    echo .
        call :myFunc %%H
)
exit /b

:myFunc
FOR /F "tokens=%1 delims=," %%I IN ("%string%") Do (

    echo String WITHOUT stripping characters: %%I 
    set currentParameter=%%I
    set currentParameter=%currentParameter:~1,-1%

    echo String WITH stripping characters: %currentParameter% 

    echo .

)
exit /b   

:end

出力は次のとおりです。

.
String WITHOUT stripping characters: "-String"
String WITH stripping characters:
.
.
String WITHOUT stripping characters: "-String2"
String WITH stripping characters: ~1,-1
.

しかし、私が欲しいのは:

.
String WITHOUT stripping characters: "-String"
String WITH stripping characters: -String
.
.
String WITHOUT stripping characters: "-String2"
String WITH stripping characters: -String2
.
4

4 に答える 4

7

これがあなたを助けることを願っています。

    setlocal enabledelayedexpansion
    
    echo String WITHOUT stripping characters: %%I 
    set currentParameter=%%I
    set currentParameter=!currentParameter:~1,-1!
    echo String WITH stripping characters: !currentParameter! 
于 2014-03-07T04:54:54.810 に答える
3

このスクリプトは、ENABLEDELAYEDEXPANSION を利用しています。ご存じない方のために説明すると、バッチ スクリプトは for コマンドと if コマンドをすべて 1 つにまとめて実行します。したがって、次の場合:

if true==true (
@echo off
set testvalue=123
echo %testvalue%
pause >NUL
)

echo %testvalue% が実行されると、テスト値が変更されたことを認識していないため、何も出力しません。delayexpnsion を使用すると、スクリプトはその値をそのまま読み取ることができ、前に述べた問題を忘れることができます。%testvalue% と同じように使用しますが、!testvalue! を使用することもできます。これを修正するには:

if true==true (
@echo off
set testvalue=123
echo !testvalue!
pause >NUL
)
  • 123 をエコーし​​ます。

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set string="-String","-String2"
Set count=0

For %%j in (%string%) Do Set /A count+=1

FOR /L %%H IN (1,1,%COUNT%) DO ( 
echo .
call :myFunc %%H
)

exit /b
:myFunc

FOR /F "tokens=%1 delims=," %%I IN ("%string%") Do (
echo String WITHOUT stripping characters: %%I 
set currentParameter=%%I
set currentParameter=!currentParameter:~1,-1!
echo String WITH stripping characters: !currentParameter! 
echo .
)

exit /b   
:end

〜アレックス

于 2016-01-02T21:23:03.520 に答える