根据开头的数据将文本文件拆分为多个文件

时间:2012-09-20 20:30:24

标签: text vbscript batch-file

我正在寻找通过Windows批处理文件或vbscript将文件A分成两个(文件B和文件C)的方法。如果您能提供示例代码,我将非常感谢!!

File A
------------------------------
'H',123,'1st'
'D',123,'1st'
'D',123,'2nd'
'D',123,'3rd'
'H',456,'2nd'
'D',456,'1st'
'D',456,'2nd'
'D',456,'3rd'
------------------------------

File B
------------------------------
'H',123,'1st'
'H',456,'2nd'
------------------------------

File C
------------------------------
'D',123,'1st'
'D',123,'2nd'
'D',123,'3rd'
'D',456,'1st'
'D',456,'2nd'
'D',456,'3rd'
------------------------------

3 个答案:

答案 0 :(得分:2)

findstr /bl "'H'" a.txt >b.txt
findstr /bl "'D'" a.txt >c.txt

答案 1 :(得分:0)

你也可以这样编程:

for /f "tokens=1-3 delims=," %%a in (File_A) do (
  if "%%a"=="'H'" echo %%a,%%b,%%c>>File_B
  if "%%a"=="'D'" echo %%a,%%b,%%c>>File_C
)

我相信这种方法可能会更慢,但它可以让你更精细地调整你的条件或操纵数据,而不必学习REGEX(FINDSTR实现得很差)。

答案 2 :(得分:0)

为了完整性或教育目的,使用VBS解决方案 每个找到的字母的输出流对象将保留为字典中的值。

Option Explicit
Dim fso, dic, ts_in, ts_out, s, key, INFILE, OUTDIR
Set fso = WScript.CreateObject("Scripting.Filesystemobject")
Set dic = CreateObject("scripting.dictionary")

INFILE = "c:\temp\infile.txt"
OUTDIR = Left (INFILE, InstrRev (INFILE, "\"))  'same folder as INFILE's

Set ts_in = fso.OpenTextFile (INFILE)
Do Until ts_in.AtEndOfStream
    s = ts_in.ReadLine
    key = Replace (Left (s, InStr (s, ",")-1), "'", "")
    If Not dic.Exists (key) Then
        Set ts_out = fso.CreateTextFile (OUTDIR & key & ".txt")
        dic.Add key, ts_out
    End If
    Set ts_out = dic(key)
    ts_out.writeLine s
Loop
ts_in.Close

For Each ts_out In dic.Items
    ts_out.Close
Next