How to trim leading and trailing white-spaces by a single command?

后端 未结 2 1484
长发绾君心
长发绾君心 2021-01-24 03:06

Supposing you have a string value in a variable STRING, how can you remove leading and trailing whitespaces with a single command (line)?

For instance, the

相关标签:
2条回答
  • 2021-01-24 04:07

    Concerning leading whitespaces only, the following code works (_ means TAB):

    set "STRING=  two spaces, trimmed text string, space-tab-space _ "
    
    rem no "delims=" option given, so defaulting to spaces and tabs:
    for /F "tokens=* eol= " %%S in ("%STRING%") do set "LEFTTRIMMED=%%S"
    
    echo "%LEFTTRIMMED%"
    

    However, the trailing whitespaces are still present; but they can removed by the approaches shown in this thread.

    0 讨论(0)
  • 2021-01-24 04:10

    It is not possible to trim both spaces and tabs in a single line, but just for spaces you may use this trick:

    @echo off
    setlocal EnableDelayedExpansion
    
    set "x=  two spaces, trimmed text string, space-space-space   "
    echo "%x%"
    
    rem The single line:
    set "word=%x: =" & (if "!word!" neq "" set "x2=!x2! !word!") & set "word=%" & set "x2=!x2:~1!"
    
    echo "%x2%"
    
    0 讨论(0)
提交回复
热议问题