Merge every 2nd line with previous line in batch scripting

  • 9 months ago
Comment

ChatGPT
1 / 1

You can achieve merging every second line with the previous line in a text file using batch scripting. Here's a batch script that does that:

batch
@echo off
setlocal enabledelayedexpansion

set "inputFile=input.txt"
set "outputFile=output.txt"
set "tempFile=temp.txt"

if exist "%outputFile%" del "%outputFile%"

for /f "usebackq delims=" %%a in ("%inputFile%") do (
set "line=%%a"
set /a "count+=1"

if !count! equ 2 (
set /p "previousLine="<"%tempFile%"
echo !previousLine!!line!>>"%outputFile%"
set "count=0"
) else (
echo !line!>"%tempFile%"
)
)

if exist "%tempFile%" del "%tempFile%"

echo Merging complete.

Replace "input.txt" and "output.txt" with the appropriate file names. This script reads each line from the input file, merges every second line with the previous line, and writes the merged lines to the output file.

Note that this script assumes the input lines don't contain special characters that need escaping.

Keep in mind that batch scripting might not be the most efficient way to perform this task, especially for larger files. If you're working with large files or need more advanced text processing, consider using other scripting languages like Python, PowerShell, or tools like AWK.