Remove trailing spaces from a file using Windows batch?

前端 未结 7 1342
借酒劲吻你
借酒劲吻你 2020-12-02 02:33

How could I trim all trailing spaces from a text file using the Windows command prompt?

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 02:56

    There is a nice trick to remove trailing spaces based on this answer of user Aacini; I modified it so that all other spaces occurring in the string are preserved. So here is the code:

    @echo off
    setlocal EnableDelayedExpansion
    
    rem // This is the input string:
    set "x=  This is   a text  string     containing  many   spaces.   "
    
    rem // Ensure there is at least one trailing space; then initialise auxiliary variables:
    set "y=%x% " & set "wd=" & set "sp="
    
    rem // Now here is the algorithm:
    set "y=%y: =" & (if defined wd (set "y=!y!!sp!!wd!" & set "sp= ") else (set "sp=!sp! ")) & set "wd=%"
    
    rem // Return messages:
    echo  input: "%x%"
    echo output: "%y%"
    
    endlocal
    

    However, this approach fails when a character of the set ^, !, " occurs in the string.

提交回复
热议问题