Remove leading and trailing spaces from text (Windows Command Prompt)
Removing leading and trailing spaces from lines in text in a file by means of batch file and Windows Command Prompt (CMD):
@ECHO OFF
SETLOCAL EnableDelayedExpansion
REM Setting the file to remove leading and trailing spaces from
SET "FILE=file.txt"
REM Creating and setting the output file
TYPE NUL > output.txt
SET "OUTFILE=output.txt"
REM Creating a temporary file for interim storage
SET "TMP=%TEMP%\FILES_%RANDOM%.TMP"
TYPE NUL > "%TMP%"
FOR /F "USEBACKQ DELIMS=" %%G IN ("%FILE%") DO (
REM Disabling delayed expansion to preserve exclamation marks (!) in input text
SETLOCAL DisableDelayedExpansion
REM Removing leading spaces
FOR /F "TOKENS=* DELIMS= " %%H IN ("%%G") DO (
SET "NOSPACES=%%H"
)
REM Re-enabling delayed expansion
SETLOCAL EnableDelayedExpansion
SET "NOSPACES=!NOSPACES!"
REM Removing trailing spaces by calling a subroutine
CALL :REMTRAIL
REM Safing ECHO to handle exclamation marks (!) and special characters
ECHO(!NOSPACES!>>"%TMP%"
ENDLOCAL
ENDLOCAL
)
REM Subroutine to remove trailing spaces
:REMTRAIL
IF "!NOSPACES:~-1!"==" " (
SET "NOSPACES=!NOSPACES:~0,-1!"
GOTO REMTRAIL
)
REM Sorting the contents of the temporary file alphabetically and writing the result to the output file
SORT "%TMP%" /O "%OUTFILE%"
Links
- Batch File Replace Exclamation Mark with Escaped Exclamation Mark stackoverflow.com/questions/13355733/batch-file-replace-exclamation-mark-with-escaped-exclamation-mark
Operating systems
- Windows