使用批处理将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 (

相关内容