CMD or Powershell command to combine (merge) corresponding lines from two files

前端 未结 6 1685
说谎
说谎 2020-11-29 12:56

Is it possible using CMD and Powershell to combine 2 files into 1 file like this:

file1-line1 tab file2-line1
file1-line2 tab file2-line2
file1-line3 tab file2-li         


        
6条回答
  •  盖世英雄少女心
    2020-11-29 13:28

    Probably the simplest solution is to use a Windows port of the Linux paste utility (e.g. paste.exe from the UnxUtils):

    paste C:\path\to\file1.txt C:\path\to\file2.txt
    

    From the man page:

    DESCRIPTION

    Write lines consisting of the sequentially corresponding lines from each FILE, separated by TABs, to standard output.


    For a PowerShell(ish) solution, I'd use two stream readers:

    $sr1 = New-Object IO.StreamReader 'C:\path\to\file1.txt'
    $sr2 = New-Object IO.StreamReader 'C:\path\to\file2.txt'
    
    while ($sr1.Peek() -ge 0 -or $sr2.Peek() -ge 0) {
      if ($sr1.Peek() -ge 0) { $txt1 = $sr1.ReadLine() } else { $txt1 = '' }
      if ($sr2.Peek() -ge 0) { $txt2 = $sr2.ReadLine() } else { $txt2 = '' }
    
      "{0}`t{1}" -f $txt1, $txt2
    }
    

    This avoids having to read the two files entirely into memory before merging them, which bears the risk of memory exhaustion for large files.

提交回复
热议问题