Reputation: 141
My txt file looks like:
A1;A2;A3
B1;B2
I want to split it like:
A1;;;A2
A2;;;A3
A3;;;A3
B1;;;B2
B2;;;B2
The rule is: For each line take two adjacent elements and create a new output line with them, for the last element of a line: create also a new output line, but use the element twice.
Here is my try:
(
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%
But it gives the wrong format:
A1;;;A2
A1;;;B2
B1;;;A2
B1;;;B2
How can I use batch commands to split the lines so that the expected result is obtained?
PS: A1, A2, B1 etc. are just some string examples, I can have various strings
Here is an example of a file content:
XB8998901;XB8998900;8051191;24048271;24048270
XB0134812;XB0134810;XB0134801;XB0134800
XB6312701;XB6312700
XB6314201;XB6314200
The ouput should look like:
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
Upvotes: 3
Views: 133
Reputation: 56154
@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 (your example file):
XB8998901;XB8998900;8051191;24048271;24048270
XB0134812;XB0134810;XB0134801;XB0134800
XB6312701;XB6312700
XB6314201;XB6314200
compare.txt (desired output from your example):
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
Output:
Vergleichen der Dateien new.txt und compare.txt
FC: Keine Unterschiede gefunden
(Translation: Comparing files new.txt and compare.txt
; FC: no differences encountered
)
Upvotes: 1
Reputation: 15470
Use this:
@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
Upvotes: 0