如何在多个txt文件中用单个空格替换多个空格?

时间:2018-06-18 13:21:19

标签: batch-file cmd

我已经找到了如何用单个文件中的单个空格替换多个空格但我有40个文件可以做同样的事情(可能会更多,这根据我的分析而有所不同)

程序在"列"。

之间保存带有不同空格的txt文件

例:

Position           Depth               SI
*****************************************
 655699.24         65.61    1.00
 655559.32        176.41    1.00
 655391.55        289.25    1.00
 655205.71        428.69    1.00
 655094.18        518.95    1.00
 653459.86       1611.16    1.00
 653277.26       1743.64    1.00
 653525.66       1602.15    1.00
 653596.39       1573.19    1.00
 653585.57       1591.86    1.00
 653548.80       1628.71    1.00
 653523.38       1655.96    1.00
 653494.68       1688.01    1.00
 653427.01       1729.50    1.00
 653327.08       1782.66    1.00
 653208.49       1832.50    1.00

我已经使用过:

@ECHO OFF
SETLOCAL
::
:: delete first line/lines
:: and replace each occurrence of 2 or more spaces
:: by a delimiter
::
DEL output.txt   2>nul /F /Q
:: replace with ->
SET delim= 
:: set number of lines to delete 
FOR /f "skip=1delims=" %%i IN (L1.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
>>output.txt ECHO %newline%
GOTO :eof$

使用此代码我将输入和输出文件的名称替换为40次,是否有任何自动替换空间的方法,我不需要手动替换此代码中的输入和输出文件的名称?

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您需要两个for,一个简单的迭代文件,一个for /f来解析内容。

这很容易,因为defalt分隔符是空格,连续分隔符只计为一个,前导分隔符被忽略。
添加eol=*以删除星号行,并在其间保存带引号的tokens=1-3,并且您有一个完美的.csv文件。

EDIT将输出分隔符更改为变量并删除了引号。

:: Q:\Test\2018\06\18\SO_50910509.cmd
@Echo off
Set "Delim=,"
For %%F in (sample*.txt) do (
  ( for /f "eol=*tokens=1-3" %%A in ('type %%F') do @Echo=%%A%Delim%%%B%Delim%%%C
  ) >"%%~nF.csv"
)

示例输出:

> type sample.csv
Position,Depth,SI
655699.24,65.61,1.00
655559.32,176.41,1.00
655391.55,289.25,1.00
655205.71,428.69,1.00
...snip...

答案 1 :(得分:0)

您还可以使用批处理文件中的PowerShell将每个系列的多个空格字符减少为一个:

@PowerShell -NoP "GCI 'C:\Users\kvratto\MyFolder' -Fi *.txt|Select -Exp FullName|%%{(GC $_) -Replace '\s+',' '|SC $_}"

只需将C:\Users\kvratto\MyFolder调整到包含.txt文件的保留目录

相关问题