0

I'm trying to split up the output of a file and name them based on what's in the file. Example input file:

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

I would like break that into separate files

File1: 192.168.1.1.txt

NMAP for 192.168.1.1
blah 1.1.1.1
blah blah
blah

File2: 192.168.1.2.txt

NMAP for 192.168.1.2
blah 2.2.2.2
blah blah
blah

file etc..

I see I can do it with AWK, but I can't install unix utils on all the workstations, so I would like to do this in something that's included in windows 7 enterprise like powershell or VBS, or commandline.

Thanks!

arco444
  • 22,002
  • 12
  • 63
  • 67
Dwight
  • 15
  • 6
  • A PowerShell using some regex would be a good fit for this. Give http://stackoverflow.com/questions/24835401/powershell-regular-expression-multiple-matches/24835992#24835992 a try and if you have issues you can update your question – Matt Nov 21 '14 at 17:20
  • You writeown code here. Load your string. Use instr and left or mid to extract bits. –  Nov 21 '14 at 17:21

2 Answers2

5
Get-Content $inputFileName | Foreach-Object {
    if ($_ -match "NMAP for") {
      $outputFileName = "$($_ -replace "NMAP for ").txt"
    }
    if ($outputFileName -ne $null) {
      $_ | Add-Content $outputFileName
    }
}
KevinD
  • 3,023
  • 2
  • 22
  • 26
  • It worked very well! thank you! I have to learn powershell a bit more. I have a lot of work that will be based of this kind of work, so you have saved me an immense amount of time. – Dwight Dec 16 '14 at 16:32
0

In VBScript you'd do something like this:

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
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328