使用批次將txt檔案中的多個空格替換為一個空格

使用批次將txt檔案中的多個空格替換為一個空格

這是我得到的

    @ECHO OFF
   SETLOCAL
   ::
   :: delete first line/lines
   :: and replace each occurrence of 2 or more spaces
   :: by a delimiter
   ::
   DEL outfile.txt   2>nul /F /Q
   :: replace with ->
   SET delim= 
   :: set number of lines to delete 
   FOR /f "skip=1delims=" %%i IN (Text.txt) DO (
   SET line=%%i
   (SET newline=)
   SET count=0
   CALL :change
   )
   GOTO :eof

   :CHANGE
   SET c1=%line:~0,1%
   SET line=%line:~1%
   IF "%c1%"==" " (SET /a count+=1) ELSE (
   IF %count%==0 (SET newline=%newline%%c1%) ELSE (
   IF %count%==1 (SET newline=%newline% %c1%) ELSE (
   SET newline=%newline%%delim%%c1%)
   SET count=0
   )
   )
   IF DEFINED line GOTO CHANGE
   ::
   :: You may want to preserve trailing spaces
   :: or convert them...
   ::
   IF %count%==0 GOTO print
   IF %count%==1 SET newline=%newline% &GOTO print
   SET newline=%newline%%delim%
   :PRINT
   >>outfile.txt ECHO %newline%
   GOTO :eof

這是一個文件範例

    P1 something             232
2      232  233
10     232  232
2312   232  232
231    232 323

我不再需要刪除第一行,有人可以幫我弄清楚如何替換跳過第一行的空格嗎?

答案1

在第 11 行中,替換:

FOR /f "skip=1delims=" %%i IN (Text.txt) DO (

FOR /f "delims=" %%i IN (Text.txt) DO (

要允許對帶空格的檔案名稱使用引號,根據這個 StackOverflow 答案,您可以使用以下usebackq選項:

FOR /f "usebackq delims=" %%i IN ("text 2.txt") DO (

相關內容