powershell或vbs;根据行分隔符将文件拆分为多个部分

时间:2014-11-21 17:04:46

标签: powershell vbscript split

我正在尝试拆分文件的输出,并根据文件中的内容命名它们。 示例输入文件:

NMAP for 192.168.1.1
blah 1.1.1.1
blah blah
blah
NMAP for 192.168.1.2
blah 2.2.2.2
blah blah
blah
etc...

我想将其分解为单独的文件

File1: 192.168.1.1.txt

NMAP for 192.168.1.1
blah 1.1.1.1
blah blah
blah

文件2: 192.168.1.2.txt

NMAP for 192.168.1.2
blah 2.2.2.2
blah blah
blah

文件等..

我看到我可以用AWK做到这一点,但是我不能在所有工作站上安装unix utils,所以我想在像PowerShell或VBS或命令行这样的Windows 7企业中包含这些东西。

谢谢!

2 个答案:

答案 0 :(得分:5)

Get-Content $inputFileName | Foreach-Object {
    if ($_ -match "NMAP for") {
      $outputFileName = "$($_ -replace "NMAP for ").txt"
    }
    if ($outputFileName -ne $null) {
      $_ | Add-Content $outputFileName
    }
}

答案 1 :(得分:0)

在VBScript中,您可以执行以下操作:

Set fso = CreateObject("Scripting.FileSystemObject")

Set re = New RegExp
re.Pattern = "^nmap for "
re.IgnoreCase = True

Set outFile = Nothing
Set inFile  = fso.OpenTextFile("C:\path\to\your.txt")
Do Until inFile.AtEndOfStream
  line = inFile.ReadLine
  If re.Test(line) Then
    If Not outFile Is Nothing Then outFile.Close
    Set outFile = fso.OpenTextFile(Split(line, " ")(2) & ".txt", 2)
  End If
  If Not outFile Is Nothing Then outFile.WriteLine
Loop
inFile.Close
If Not outFile Is Nothing Then outFile.Close