merge lines from several files
I have 3 text files like this
AAA1 AAA2 AAA3 ... ...
BBB1 BBB2 BBB3 .. ..
CCC1 CCC2 CCC3 .. ..
I want to have output.txt like this
AAA1:BBB1:CCC1 AAA2:BBB2:CCC2 .. ...
now I can do this by making a loop reading a line from each file but I want to do this using sed , grep or any similar tools but I dont know how.
paste -d ':' file1.txt file2.txt file3.txt
paste is well suited to this task. Try:
paste -d ":" file1.txt file2.txt file3.txt > output.txt
The paste answer sounds like a perfect solution.
But someone (not the OP) might want a native solution that does not require downloading an executable. Something like this really should be done with a more powerful scripting language like VBScript or JScrpt.
But, since I like the challenge of solving things with batch, I thought I'd take a stab at a native batch solution, just for fun.
The OP said "now I can do this by making a loop reading a line from each file". That is easier said than done using batch!
Normally files are read using FOR /F, but there is no good way to interleave reads from multiple files using FOR /F. The only other native alternative is to use SET /P with redirected input. This technique imposes the following limitations:
- The input files must use Windows style line terminators: <carriage return><line feed>
- No input line can exceed 1021 bytes in length (disregarding the line terminators)
- Trailing control characters are stripped from each input line
In addition, each final merged line must not exceed the batch variable length limit of ~8k bytes.
One last restriction - the script can only handle up to 7 input files. The script will fail if more than 7 files are specified - I did not include any error checking.
So here is a working batch script - call it "merge.bat". Note - this batch solution is MUCH slower than other solutions like paste or scripts written in VBScript or JScript. But it does work :-)
@echo off setlocal disableDelayedExpansion ::Initialization set "inputRedirection=" set "files=2" set "lines=0" for %%F in (%*) do call :setInputRedirection setlocal enableDelayedExpansion set "inputRedirection=!inputRedirection:::=<!" ::Merge the files %inputRedirection% ( for /l %%N in (1 1 %lines%) do ( set "ln=" for /l %%I in (3 1 %files%) do ( call :readLine %%I if %%I neq %files% ( set "ln=!ln!!input!:" ) else ( echo(!ln!!input! ) ) ) ) exit /b :setInputRedirection set /a "files+=1" for %%A in (1) do ( set inputRedirection=%files%::"%%~F" %inputRedirection% for /f %%N in ('find /c /v "" ^<"%%~F"') do if %%N gtr %lines% set "lines=%%N" ) exit /b :readLine fileHandle set "input=" <&%1 set /p "input=" exit /b
To merge your files you would do:
merge.bat file1.txt file2.txt file3.txt >output.txt