1

I have two text files as A.txt and B.txt with the below contents:

A.txt

value_a1,value_a2
value_b
value_c
value_d
value_e1,value_e2

B.txt

12,14
13
15
16
23,34

I want output file C.txt as

"value_a1","12","value_a2","14"
"value_b","13"
"value_c","15"
"value_d,"16"
"value_e1,"23","value_e2","34"

Please guide me through as I am new to Batch Script.

Bali C
  • 30,582
  • 35
  • 123
  • 152
user2017841
  • 21
  • 1
  • 3
  • 1
    don't use a batch file for stuff like this. it will make you want to tear your hair out. if this needs to run on windows machines without 3rd party software try VBScript instead – hdgarrood Jan 28 '13 at 11:56

2 Answers2

3

Following code will work:

    @Echo off

    echo. >>d.txt
    type b.txt >>d.txt

    set dec=1
    For /F "usebackq tokens=1,* delims=, " %%a in ("a.txt") do call :File1 %%a %%b
    set dec1=0
    del d.txt

    exit /b

    :File1
    SET str1=%~1
    SET str2=%~2
    SET Count=1
    For /F "usebackq tokens=1,* skip=%dec% delims=," %%A in ("d.txt") do call :File2   %%A %%B
    set /a dec=%dec%+1

    exit /b

    :File2
    SET str3=%~1
    SET str4="%~2"
    IF %Count% EQU 1 (
    IF %str4%=="" (
    echo "%str1%","%str3%" >>c.txt
    set /a Count=%Count%+1
    ) ELSE (
    echo "%str1%","%str3%","%str2%",%str4% >>c.txt
    set /a Count=%Count%+1) 
    )
    exit /b 
Shirulkar
  • 484
  • 2
  • 4
2

There are many restrictions to this solution, but it is about as simple a solution as is possible with pure native batch. It is also fairly efficient for a batch solution.

@echo off
setlocal enableDelayedExpansion
<b.txt >c.txt (
  for /f delims^=^ eol^= %%L in (a.txt) do (
    set "ln="
    set /p "ln="
    set "out="
    for %%A in (%%L) do (
      for /f "tokens=1* delims=," %%a in ("!ln!") do (
        set "out=!out!,"%%A","%%a""
        set "ln=%%b"
      )
      echo !out:~1!
    )
  )
)

Limitations:

  • A.TXT cannot contain * or ? or !
  • A.TXT values must be quoted if they contain any of <space> <tab> , ; =
  • A.TXT max line length is approximately 8191 bytes
  • B.TXT cannot contain !
  • B.TXT values cannot contain , (, is strictly a delimiter)
  • B.TXT max line length is 1021 bytes
  • B.TXT lines must use Windows style terminators (carriage return/linefeed), not Unix style (linefeed)

Some of the limitations can be overcome fairly easily. Others require a lot more effort, to the point of becoming totally impractical.

dbenham
  • 127,446
  • 28
  • 251
  • 390
  • A bit mind-blowing, but I think I've worked it out. You didn't enclose the first `for`'s options but escaped some characters instead. Was that intentional or just a demonstration that it could work both ways? – Andriy M Jan 29 '13 at 07:38
  • @AndriyM - Intentional. That is the simplest syntax that disables both DELIMS and EOL (both are set to an empty string). – dbenham Jan 29 '13 at 10:38