Компьютерный форум OSzone.net  

Компьютерный форум OSzone.net (http://forum.oszone.net/index.php)
-   Скриптовые языки администрирования Windows (http://forum.oszone.net/forumdisplay.php?f=102)
-   -   [решено] можно ли батником разрезать файл по шаблону? (http://forum.oszone.net/showthread.php?t=268904)

ruslaw 27-09-2013 18:14 2224972

можно ли батником разрезать файл по шаблону?
 
Есть один текстовый файл (file.txt) в котором заключена информация на несколько html-файлов.
Примерно такой:
-------------------------------------------
<html>
<title>1</title>
<body>
1111111111
</body>
</html>
<html>
<title>2</title>
<body>
2222222222
</body>
</html>
<html>
<title>3</title>
<body>
3333333333
</body>
</html>
..........
<html>
<title>x</title>
<body>
xxxxxxxxxx
</body>
</html>
-------------------------------------------
как превратить его средствами bat-файлов (если можно) в несколько html-файлов: 1.htm, 2.htm, 3.htm .... x.htm

Iska 27-09-2013 19:40 2225013

Код:

Option Explicit

Dim strSourceFile

Dim objFSO
Dim strContent

Dim objRegExp
Dim objMatch

Dim strNewFileName

If WScript.Arguments.Count = 1 Then
        strSourceFile = WScript.Arguments.Item(0)
       
        With WScript.CreateObject("Scripting.FileSystemObject")
                If .FileExists(strSourceFile) Then
                        With .OpenTextFile(strSourceFile)
                                strContent = .ReadAll()
                                .Close
                        End With
                       
                        Set objRegExp = WScript.CreateObject("VBScript.RegExp")
                       
                        With objRegExp
                                .Pattern = "<html>[\s\S]*?<title>([\s\S]*?)</title>[\s\S]*?</html>"
                                .Global = True
                        End With
                       
                        If objRegExp.Test(strContent) Then
                                For Each objMatch In objRegExp.Execute(strContent)
                                        strNewFileName = .BuildPath(.GetParentFolderName(strSourceFile), objMatch.SubMatches(0) & ".htm")
                                        WScript.Echo "Create file [" & strNewFileName & "]."
                                       
                                        With .CreateTextFile(strNewFileName)
                                                .WriteLine objMatch.Value
                                                .Close
                                        End With
                                Next
                        Else
                                WScript.Echo "No matches"
                        End If
                Else
                        WScript.Echo "Source file [" & strSourceFile & "] not found."
                End If
        End With
Else
        WScript.Echo "Usage: cscript.exe //nologo " & WScript.ScriptName & " <Source file>"
End If

WScript.Quit 0

Сохраните код в файл с расширением «.vbs», затем просто перетащите на него Ваш «один текстовый файл (file.txt)».

P.S. Никаких проверок на содержимое внутри тэга «title» не делается. Посему, ежели там окажется какой-либо запрещённый в именах файлов символ, например «:», скрипт завершится с ошибкой.

ruslaw 27-09-2013 21:37 2225055

Фантастика!
Огромнейшее спасибо, работает!

Pet20211029 29-10-2021 12:05 2970066

Здравствуйте,.
Как прочитать текстовый файл (file.txt) из скрипта, не перетаскивая его

alpap 29-10-2021 14:05 2970078

Цитата:

Цитата Pet20211029
не перетаскивая его »

а к чему его перетаскивать, в рамках задачи:
Код:

more file.txt
что еще надо?

Pet20211029 29-10-2021 14:17 2970079

Писал про скрипт выше, от Iska.
Он пишет:
Сохраните код в файл с расширением «.vbs», затем просто перетащите на него Ваш «один текстовый файл (file.txt)».
Как его модифицировать?

Fors1k 29-10-2021 15:02 2970086

Код:

cls
$pathIn  = "D:\file.txt"
$pathOut = "D:\htmlDocs"

[Regex]::Matches((gc $pathIn -Raw), "<html>.*?</html>", 0x10).Value|ForEach{$i=1}{
   
$_|Out-File "$pathOut\$i.htm";$i++
}
 


Pet20211029 29-10-2021 15:23 2970091

Выдает ошибку Недопустимый знак " Строка 4"

alpap 29-10-2021 15:27 2970092

Pet20211029, это код для PowerShell, если что.

Pet20211029 29-10-2021 15:33 2970093

Спасибо, все же надо в vbs

Pet20211029 30-10-2021 19:05 2970185

Перебрал vbs для своих целей, теперь есть возможность указать путь к (file.txt), так же можно его или другой файл, просто перетащить на сам vbs. Может кому и пригодится.
Скрытый текст

Код:

Option Explicit
Dim objArgs, readablefile, strContent, objRegExp, objMatch, strNewreadablefile
readablefile = "file.txt"
Set objArgs = WScript.Arguments   
' Для обработки можно просто перетянуть файл на значек сценария.               
If objArgs.Count > 0 Then readablefile = objArgs(0)       

        With WScript.CreateObject("Scripting.FileSystemObject")
                If .FileExists(readablefile) Then
                        With .OpenTextFile(readablefile)
                                strContent = .ReadAll()
                                .Close
                        End With
                       
                        Set objRegExp = WScript.CreateObject("VBScript.RegExp")
                       
                        With objRegExp
                                .Pattern = "<html>[\s\S]*?<title>([\s\S]*?)</title>[\s\S]*?</html>"
                                .Global = True
                        End With
                       
                        If objRegExp.Test(strContent) Then
                                For Each objMatch In objRegExp.Execute(strContent)
                                        strNewreadablefile = .BuildPath(.GetParentFolderName(readablefile), objMatch.SubMatches(0) & ".html")
                                        'WScript.Echo "Create readablefile [" & strNewreadablefile & "]."
                                       
                                        With .CreateTextFile(strNewreadablefile)
                                                .WriteLine objMatch.Value
                                                .Close
                                        End With
                                Next
                        Else
                                WScript.Echo "No matches"
                        End If
                Else
                        WScript.Echo "Source readablefile [" & readablefile & "] not found."
                End If
        End With
WScript.Quit 0



Время: 01:39.

Время: 01:39.
© OSzone.net 2001-