![使用批处理将txt文件中的多个空格替换为一个空格](https://linux22.com/image/1543163/%E4%BD%BF%E7%94%A8%E6%89%B9%E5%A4%84%E7%90%86%E5%B0%86txt%E6%96%87%E4%BB%B6%E4%B8%AD%E7%9A%84%E5%A4%9A%E4%B8%AA%E7%A9%BA%E6%A0%BC%E6%9B%BF%E6%8D%A2%E4%B8%BA%E4%B8%80%E4%B8%AA%E7%A9%BA%E6%A0%BC.png)
这是我得到的
@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 (