How to merge two text files using batch script?

点点圈 提交于 2020-02-05 08:12:45

问题


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.


回答1:


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 



回答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.



来源:https://stackoverflow.com/questions/14561411/how-to-merge-two-text-files-using-batch-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!