批量将每行分成多行

时间:2019-12-09 15:51:34

标签: batch-file text split

我的txt文件如下:

A1;A2;A3
B1;B2

我想像这样分割它:

A1;;;A2
A2;;;A3
A3;;;A3
B1;;;B2
B2;;;B2

规则是:对于每行,请使用两个相邻的元素并用它们创建一条新的输出线,对于一行的最后一个元素:还要创建一条新的输出线,但要使用两次。

这是我的尝试:

(
    for /f "tokens=1-4 delims=;" %%a in (%FilePath%) do (
        for /f "tokens=1-4 delims=;" %%x in (%FilePath%) do (
            echo %%a;;;%%y
        )
    )
)>%FilePath_Final%

但是它给出了错误的格式:

A1;;;A2
A1;;;B2
B1;;;A2
B1;;;B2

如何使用批处理命令拆分行,以便获得预期的结果?

PS:A1,A2,B1等只是一些字符串示例,我可以有各种字符串

以下是文件内容的示例:

XB8998901;XB8998900;8051191;24048271;24048270
XB0134812;XB0134810;XB0134801;XB0134800
XB6312701;XB6312700
XB6314201;XB6314200

输出应如下所示:

XB8998901;;;XB8998900
XB8998900;;;8051191
8051191;;;24048271
24048271;;;24048270
24048270;;;24048270
XB0134812;;;XB0134810
XB0134810;;;XB0134801
XB0134801;;;XB0134800
XB0134800;;;XB0134800
XB6312701;;;XB6312700
XB6312700;;;XB6312700
XB6314201;;;XB6314200
XB6314200;;;XB6314200

2 个答案:

答案 0 :(得分:1)

@echo off
setlocal enabledelayedexpansion
set "last="
(for /f "delims=" %%a in (old.txt) do (
  for %%b in (%%a) do (
    if defined last echo !last!;;;%%b
    set "last=%%b"
  )
echo !last!;;;!last!
set "last="
))>new.txt
fc new.txt compare.txt

old.txt(您的示例文件):

XB8998901;XB8998900;8051191;24048271;24048270
XB0134812;XB0134810;XB0134801;XB0134800
XB6312701;XB6312700
XB6314201;XB6314200

compare.txt(示例中的期望输出):

XB8998901;;;XB8998900
XB8998900;;;8051191
8051191;;;24048271
24048271;;;24048270
24048270;;;24048270
XB0134812;;;XB0134810
XB0134810;;;XB0134801
XB0134801;;;XB0134800
XB0134800;;;XB0134800
XB6312701;;;XB6312700
XB6312700;;;XB6312700
XB6314201;;;XB6314200
XB6314200;;;XB6314200

输出:

Vergleichen der Dateien new.txt und compare.txt
FC: Keine Unterschiede gefunden

(翻译:{{1​​}}; Comparing files new.txt and compare.txt

答案 1 :(得分:0)

使用此:

@echo off
Setlocal enabledelayedexpansion 
for /f "tokens=1,2,3 delims=;" %%a in ('type  pathoffile ^| find "A"') do (set 1=%%a & set 2=%%b & set 3=%%c)
for /f "tokens=1,2 delims=;" %%a in ('type  pathoffile ^| find "B"') do (set 4=%%a & set 5=%%b)
set n=1
:loop
set /a m=n+1
if "!%n%:~0,1!"=="!%m%:~0,1!" (
  echo !%n%!;;;!%m%! >>filepath_final
) else (
  echo!%n%!;;; >>filepath_final
)
set /a n=n+1
if %m% equ 5 goto :eof 
goto loop