|
Компьютерный форум OSzone.net » Программирование, базы данных и автоматизация действий » Скриптовые языки администрирования Windows » CMD/BAT - [решено] замена подстрок из одного файла в другой |
|
CMD/BAT - [решено] замена подстрок из одного файла в другой
|
Новый участник Сообщения: 39 |
Имеются 2 файла:
build.prop - файл к которому применяется патч path.txt - файл патч для build.prop new_build.prop - build.prop с замененными строками ================================= файл build.prop состоит так: # Комментарий Переменная1=значение Переменная2=значение Переменная3=значение ... # Комментарий ПеременнаяN=значение .... ================================= В файле path.txt такой же,но без комментариев ================================= Необходимо Значений найденных переменных заменить из файла path.txt в build.prop, и получившийся файл переименовать в new_build.prop ================================= Например: build.prop .... name=rea brand=apple model=no1 .... path.txt name=cool model=abc new_build.prop .... name=cool brand=apple model=abc ..... |
|
Отправлено: 20:23, 18-03-2017 |
Ветеран Сообщения: 27449
|
Профиль | Отправить PM | Цитировать Скрытый текст
Option Explicit Dim strSourceFile Dim strPatternFile Dim strDestFile Dim strContent Dim strLine Dim arrPattern Dim objDictionary Dim strKey strSourceFile = "C:\Мои проекты\0053\build.prop" strPatternFile = "C:\Мои проекты\0053\path.txt" strDestFile = "C:\Мои проекты\0053\new_build.prop" With WScript.CreateObject("Scripting.FileSystemObject") If .FileExists(strSourceFile) Then If .FileExists(strPatternFile) Then With .OpenTextFile(strPatternFile) strContent = .ReadAll() .Close End With Set objDictionary = WScript.CreateObject("Scripting.Dictionary") For Each strLine In Split(strContent, vbLf) strLine = Trim(strLine) If Len(strLine) > 0 Then arrPattern = Split(strLine, "=") objDictionary.Add Trim(arrPattern(0)), Trim(arrPattern(1)) End If Next With .OpenTextFile(strSourceFile) strContent = .ReadAll() .Close End With With WScript.CreateObject("VBScript.RegExp") .IgnoreCase = True .Global = True For Each strKey In objDictionary.Keys .Pattern = "[\f\t\v]*(" & strKey & ")[\f\t\v]*=[\f\t\v]*?.*[\f\t\v]*" If .Test(strContent) Then strContent = .Replace(strContent, "$1=" & objDictionary.Item(strKey)) End If Next End With With .CreateTextFile(strDestFile, True) .Write strContent .Close End With objDictionary.RemoveAll Set objDictionary = Nothing Else WScript.Echo "Can't find pattern file [" & strPatternFile & "]." WScript.Quit 2 End If Else WScript.Echo "Can't find source file [" & strSourceFile & "]." WScript.Quit 1 End If End With WScript.Quit 0 Вообще-то, патч по-англицки именуется «patch». |
Отправлено: 07:19, 19-03-2017 | #2 |
Для отключения данного рекламного блока вам необходимо зарегистрироваться или войти с учетной записью социальной сети. Если же вы забыли свой пароль на форуме, то воспользуйтесь данной ссылкой для восстановления пароля. |
Новый участник Сообщения: 39
|
Профиль | Сайт | Отправить PM | Цитировать Iska, А можно сделать, чтобы абсолютные пути не использовались? (чтобы скрипт работал из любой папки)
Например как в батнике: strSourceFile = "%dp0\0053\build.prop" strPatternFile = "%dp0\0053\path.txt" strDestFile = "%dp0\0053\new_build.prop" Возможно сделать что-то подобное? |
Последний раз редактировалось vngreez@vk, 19-03-2017 в 09:20. Отправлено: 08:32, 19-03-2017 | #3 |
Ветеран Сообщения: 27449
|
Профиль | Отправить PM | Цитировать Можно. Только то, что Вы приводите в пример — это вовсе не «из любой папки», а строго «из того же каталога, в котором расположен пакетный файл». Будем считать, что на самом деле Вас интересует именно второе (хоть это и не есть правильно).
Скрытый текст
Option Explicit Dim strSourceFile Dim strPatternFile Dim strDestFile Dim strPath2Script Dim strContent Dim strLine Dim arrPattern Dim objDictionary Dim strKey strSourceFile = "build.prop" strPatternFile = "path.txt" strDestFile = "new_build.prop" With WScript.CreateObject("Scripting.FileSystemObject") strPath2Script = .GetParentFolderName(WScript.ScriptFullName) strSourceFile = .BuildPath(strPath2Script, strSourceFile) strPatternFile = .BuildPath(strPath2Script, strPatternFile) strDestFile = .BuildPath(strPath2Script, strDestFile) If .FileExists(strSourceFile) Then If .FileExists(strPatternFile) Then With .OpenTextFile(strPatternFile) strContent = .ReadAll() .Close End With Set objDictionary = WScript.CreateObject("Scripting.Dictionary") For Each strLine In Split(strContent, vbLf) strLine = Trim(strLine) If Len(strLine) > 0 Then arrPattern = Split(strLine, "=") objDictionary.Add Trim(arrPattern(0)), Trim(arrPattern(1)) End If Next With .OpenTextFile(strSourceFile) strContent = .ReadAll() .Close End With With WScript.CreateObject("VBScript.RegExp") .IgnoreCase = True .Global = True For Each strKey In objDictionary.Keys .Pattern = "[\f\t\v]*(" & strKey & ")[\f\t\v]*=[\f\t\v]*?.*[\f\t\v]*" If .Test(strContent) Then strContent = .Replace(strContent, "$1=" & objDictionary.Item(strKey)) End If Next End With With .CreateTextFile(strDestFile, True) .Write strContent .Close End With objDictionary.RemoveAll Set objDictionary = Nothing Else WScript.Echo "Can't find pattern file [" & strPatternFile & "]." WScript.Quit 2 End If Else WScript.Echo "Can't find source file [" & strSourceFile & "]." WScript.Quit 1 End If End With WScript.Quit 0 |
Отправлено: 10:48, 19-03-2017 | #4 |
![]() |
Участник сейчас на форуме |
![]() |
Участник вне форума |
![]() |
Автор темы |
![]() |
Сообщение прикреплено |
| |||||
Название темы | Автор | Информация о форуме | Ответов | Последнее сообщение | |
CMD/BAT - [решено] Замена текста одного файла, текстом из другого файла | ninjaman | Скриптовые языки администрирования Windows | 8 | 11-03-2017 00:59 | |
CMD/BAT - [решено] Замена текста из одного файла в другом | blackeangel | Скриптовые языки администрирования Windows | 6 | 20-11-2015 11:07 | |
CMD/BAT - [решено] поиск и замена из одного файла в другом | alexmoreman | Скриптовые языки администрирования Windows | 6 | 27-05-2013 09:33 | |
CMD/BAT - [решено] Сравнение файлов и замена значения из одного файла в другой. | Aleks911tat | Скриптовые языки администрирования Windows | 12 | 25-08-2012 22:27 | |
CMD/BAT - Перенос строк из одного файла в другой | jackscorpse | Скриптовые языки администрирования Windows | 0 | 25-08-2012 00:31 |
|