Leo92
Leo92

Reputation: 744

how to join 2 lines using batch file

I have a text file that have unknown number of lines , some lines begins with patterns , I want to join the lines that begins with patterns with the next line , so for example

name=jimmy
age=19 id=23423 site=www.xxx.com
bla bla
name=katy
age=15 id=234543 site=www.yyy.com
name=ross
age=29 id=54564 site=www.ZZZZ.com

the output should be

name=jimmy age=19 id=23423 site=www.xxx.com
 bla bla bla
name=katy age=15 id=234543 site=www.yyy.com
name=ross age=29 id=54564 site=www.ZZZZ.com

so the pattern is 'name' and it should join next line I thougt to use sed but I dont know how help please

Upvotes: 0

Views: 3752

Answers (2)

Aacini
Aacini

Reputation: 67326

@echo off
setlocal EnableDelayedExpansion
set pattern=name
set patternLen=4
call :ProcessFile < input.txt > output.txt
goto :EOF

:ProcessFile
set line=
set /P line=
if not defined line exit /B
if "!line:~0,%patternLen%!" equ "%pattern%" (
   set /P nextLine=
   set "line=!line! !nextLine!"
)
echo !line!
goto ProcessFile

Previous Batch file have the problem that it ends at the first empty line in the input file. However, this problem may be fixed if needed.

Upvotes: 1

Eitan T
Eitan T

Reputation: 32930

Well, here's a straightforward script:

@echo off
setlocal enabledelayedexpansion
set "INPUT_FILE=input.txt"
set "OUTPUT_FILE=output.txt"
set prev=
for /f "tokens=*" %%f in (%INPUT_FILE%) do (
    for /f "tokens=1,2 delims==" %%g in ("%%f") do (
        if "!prev!" neq "" (
            echo !prev! %%f >>%OUTPUT_FILE%
            set prev=
        ) else (
            if "%%g" equ "name" (
                set prev=%%f
            ) else (
                echo %%f >>%OUTPUT_FILE%
                set prev=
            )
        )
    )
)

Upvotes: 1

Related Questions