从多个文件中提取所有行

时间:2015-09-23 11:50:42

标签: string csv batch-file terminal

我有3个文件:

  • 第一个文件是ID列表
  • 第二个文件是源字符串
  • 第三个文件由目标字符串组成。

例如

File 1
3952276-0-1
3952276-0-2
3952276-0-3
3952276-0-4
3952276-0-5
3952276-0-6
3952276-0-7
3952276-0-8
3952276-0-9
3952276-0-10

File 2
source-string1
source-string2
source-string3
source-string4
source-string5
source-string6
source-string7
source-string8
source-string9
source-string10

File 3
target-string1
target-string2
target-string3
target-string4
target-string5
target-string6
target-string7
target-string8
target-string9
target-string10

我希望csv中的结果文件像一样,如果目标字符串与源字符串相同,不要复制 在"& #34; ...离开""如果目标字符串与源

相同,则为空
"3952276-0-1","source-string1","target-string1"
"3952276-0-2","source-string2","target-string2"
"3952276-0-3","source-string3","target-string3"

我是怎么做到的? Thx提前

2 个答案:

答案 0 :(得分:2)

@echo off
setlocal EnableDelayedExpansion

rem File 1 is read with the FOR command
rem File 2 and File 3 are read via standard handles 3 and 4, respectively

3< file2.txt 4< file3.txt (for /F "delims=" %%a in (file1.txt) do (
   set /P "source=" <&3
   set /P "target=" <&4
   if "!target!" neq "!source!" (
      echo "%%a","!source!","!target!"
   ) else (
      echo "%%a","!source!",""
   )
)) > output.txt

有关用于阅读多个文件的方法的更多详细信息,请参阅this post

答案 1 :(得分:0)

这应该有效:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET file1=1.txt
SET file2=2.txt
SET file3=3.txt
SET targetfile=target.txt
TYPE NUL>%targetfile%
SET i=0
FOR /F %%l IN (%file1%) DO (
    SET x!i!=%%l
    SET /a i=!i!+1
)
SET i=0
FOR /F %%l IN (%file2%) DO (
    SET y!i!=%%l
    SET /a i=!i!+1
)
SET i=0
FOR /F %%l IN (%file3%) DO (
    SET z!i!=%%l
    SET /a i=!i!+1
)
SET /a i=!i!-1
FOR /L %%n IN (0,1,!i!) DO (
    ECHO "!x%%n!","!y%%n!","!z%%n!">>%targetfile%
)

首先,我们将file1的每一行加载到变量x1,x2,x3,...,xi中。然后我们对第二和第三个文件做同样的事情并将它们存储在y1,...,y1和z1,...,zi中。这里要求所有三个文件具有相同的行数。

最后我们写了&#34; xi&#34;,&#34; yi&#34;,&#34; zi&#34;进入目标文件。