Каждый день мы получаем плоский текстовый файл. В некоторые дни существуют строки в файле, который должен быть удален, прежде чем он сможет быть обработан. Эти строки могут появиться в различных местах, но всегда запускаться с символов 6999 или 7999. Мы хотели бы запустить скрипт, который удалит эти конкретные строки. Однако и это - путь вне меня, любой, где существует строка, которая запускается 6999 будет строка сразу перед ним, который запускается 5442, который также должен быть удален, но только если это сразу появляется перед 6 999 строками.
Мы - магазин Windows и запустили бы этот скрипт как часть простого пакетного файла в Windows. Мы не используем Unix или Linux, ни требуем.
Расширение файла отражает дату. сегодняшний файл является файлом 100621, завтрашний будет файл 100622. Я испытываю затруднения из-за этого аспекта, поскольку кажется, что vbscript не нравится файл.*
Вот образец текстового файла:
4006006602 03334060000100580
40060066039 0334070000100580
700600000011571006210060001255863
544264287250111000025000000000040008000801
6999001000000000000000000000000000000000000000000000000000
6999001000000000000000000000000000000000000000000000000000
6999001000000000000000000000000000000000000000000000000000
799900000011571006210030000000000
8007000000115710062102530054008920
Мы хотели бы удалить 5 строк в этом файле (5 442 строки, три 6 999 строк и 7 999 строк).
Вот образец сценария, который я нашел на этом сайте, изменил и имел некоторый успех, но не знаю, способ удалить строки (только знают, как заменить данные в строке). Я понимаю, что это будет или нуждаться в основных модификациях или должно быть выведено в целом, но я отправляю это для обеспечения идеи того, что я думаю, что мы ищем. Я поместил это в каталог с cscript.exe и называю его от простого пакетного файла:
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\temp\file.100621"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If InStr(strLine,"6999")> 0 Then
strLine = Replace(strLine,"6999","delete line")
End If
WScript.Echo strLine
Loop
Который получает меня это:
40060066039 0334070000100580
700600000011571006210060001255863
544264287250111000025000000000040008000801
delete line001000000000000000000000000000000000000000000000000000
delete line001000000000000000000000000000000000000000000000000000
delete line001000000000000000000000000000000000000000000000000000
799900000011571006210030000000000
8007000000115710062102530054008920
Закрыть! просто потребность удалить строки вместо записи "удаляет строку". Таким образом, вот мои определенные потребности на основе того, что я знаю:
Я внес некоторые изменения, чтобы попытаться удалить пустую строку, я также добавил функцию для циклического просмотра вывода файл и удалите все пустые строки. Надеюсь, это сработает.
Select Case Wscript.Arguments.Count
case 1:
strInput = GetFile(WScript.Arguments(0))
RemoveUnwantedLines strInput, strInput
RemoveBlankLines strInput
case 2:
strInput = GetFile(WScript.Arguments(0))
strOutput = Wscript.Arguments(1)
RemoveUnwantedLines strInput, strOutput
RemoveBlankLines strOutput
End Select
Function GetFile(strDirectory)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strDirectory)
dateLastModified = Null
strFile = ""
For Each objFile in objFolder.Files
If IsNull(dateLastModified) Then
dateLastModified = objFile.DateLastModified
strFile = objFile.Path
ElseIf dateLastModified < objFile.DateLastModified Then
dateLastModified = objFile.DateLastModified
strFile = objFile.Path
End If
Next
GetFile = strFile
End Function
Sub RemoveUnwantedLines(strInputFile, strOutputFile)
'Open the file for reading.
Set objFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(strInputFile,1)
'Read the entire file into memory.
strFileText = objFile.ReadAll
'Close the file.
objFile.Close
'Split the file at the new line character. *Use the Line Feed character (Char(10))
arrFileText = Split(strFileText,Chr(10))
'Open the file for writing.
Set objFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(strOutputFile,2,true)
'Loop through the array of lines looking for lines to keep.
For i = LBound(arrFileText) to UBound(arrFileText)
'If the line is not blank process it.
If arrFileText(i) <> "" Then
'If the line starts "5442", see if the next line is "6999".
If Left(arrFileText(i),4) = "5442" Then
'Make sure the next line exists (Don't want an out of bounds exception).
If i + 1 <= UBound(arrFileText)Then
'If the next line is not "6999"
If Left(arrFileText(i + 1), 4) <> "6999" Then
'Write the "5442" line to the file.
objFile.WriteLine(arrFileText(i))
End If
Else
'If the next line does not exist, write the "5442" line to the file (without a new line).
objFile.WriteLine(arrFileText(i))
End If
'If the line does not start with "6999" and the line does not start with "7999".
Elseif Left(arrFileText(i),4) <> "6999" AND Left(arrFileText(i),4) <> "7999" Then
'Write the line to the file.
objFile.WriteLine(arrFileText(i))
End If
End If
Next
'Close the file.
objFile.Close
Set objFile = Nothing
End Sub
Sub RemoveBlankLines(strInputFile)
Set objFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(strInputFile,1)
'Read the entire file into memory.
strFileText = objFile.ReadAll
'Close the file.
objFile.Close
'Split the file at the new line character.
arrFileText = Split(strFileText,VbNewLine)
Set objFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(strInputFile,2,true)
'Loop through the array of lines looking for lines to keep.
For i = LBound(arrFileText) to UBound(arrFileText)
'If the line is not blank.
if arrFileText(i) <> "" Then
'If there is another element.
if i + 1 <= UBound(arrFileText) Then
'If the next element is not blank.
if arrFileText(i + 1) <> "" Then
'Write the line to the file.
objFile.WriteLine(arrFileText(i))
Else
'Write the line to the file (Without a blank line).
objFile.Write(arrFileText(i))
End If
Else
'Write the line to the file (Without a blank line).
objFile.Write(arrFileText(i))
End If
End If
Next
'Close the file.
objFile.Close
Set objFile = Nothing
End Sub
Чтобы использовать его, вызовите его из командной строки одним из двух способов.
RemoveUnwantedLines "C:\TestDirectory\" "C:\Output.txt"
или
RemoveUnwantedLines "C:\TestDirectory\"
Это был бы мой псевдоалгоритм для решения этой проблемы:
(Я скорее научу вас своим мыслям о том, как я могу решить эту проблему, чем предоставить сам код)
Сделать файл используемым в качестве параметра (чтобы он может быть гибким) или создать папку «спулер», которую эта программа проверяет на наличие нового содержимого при запуске, например «Входящие» для почты. Тогда вам также понадобится «Исходящие». Таким образом, вы можете обрабатывать файлы по мере их поступления, не зная, как они названы, и перемещать их в «Исходящие» при обработке.
Сделайте простой "конфигурационный" файл и для этой программы. Каждая строка может представлять «фильтр», и позже вы можете добавить действия к строкам, если это необходимо.
7999 удалить
6999 удалить
5442 удалить
как в [шаблон] [действие]
Теперь, после считывания конфигурации в массив «ключей», затем проверьте «Входящие» на наличие файлов . Для каждого файла обработайте его набором ключей.
Обработка файла "XXXXXXXXX.log" (или любого другого имени) Загрузите все строки, если их не слишком много, или строку чтения, чтобы захватить одну (в зависимости от производительности и использования памяти)
Для каждой строки возьмите первые 4 буквы из строки ...
Теперь нам понадобится строка для синтаксического анализа:
sLine = left(readline(input filestream), 4)
, поскольку нам нужны только первые 4 символа, чтобы решить, нужно ли нам ее сохранить.
Если эта «sLine» (строка) находится в нашем массиве фильтров / шаблонов, то у нас есть совпадение… выполните то действие, которое мы настроили (в вашей текущей настройке - строка delete = ignore).
6а. Если игнорировать, перейдите к следующей строке в текстовом файле, перейдите к # 7
6b. Если в массиве шаблонов совпадений нет, нам нужно сохранить строку. Запишите это в поток OUTPUT.
Если больше строк, NEXT (goto # 5)
Закройте входной и выходной файл.
Удалить / переместить входной файл из папки «Входящие» (возможно, для резервного копирования?)
Если в каталоге [входящие] будет больше файлов, затем выполните синтаксический анализ ... перейдите к # 4
Это не просто VBSCRIPT, а идея алгоритма Ann для любой язык ...
Я надеюсь, что вы сможете увидеть в нем мою идею, иначе вы просто прокомментируете это, и я постараюсь уточнить его. Надеюсь, я дал вам отличный ответ.
Я думаю, что это сработает (но я не настолько хорош в VBS, поэтому никаких обещаний):
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\temp\file.100621"
Set objFile = objFS.OpenTextFile(strFile)
Dim cachedLine
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If Len(cachedLine) > 0 And InStr(strLine,"6999") = 1 Then
WScript.Echo cachedLine
End If
cachedLine = ""
If InStr(strLine,"5442") = 1 Then
cachedLine = strLine
Else
If InStr(strLine,"6999") = 1 Or InStr(strLine,"7999") = 1 Then
' do nothing
Else
WScript.Echo strLine
End If
End If
Loop
Обратите внимание, что я думаю, вы проверяли, содержат ли строки числа где-нибудь, но вы сказали что правило было, если они начинали с чисел, поэтому я делаю <> 1
, а не > 0
.
Хорошо, вот последний скрипт, великолепно собранный Tester101. Этот сценарий удаляет строки, которые не нужны, как описано выше. Он также имеет дело с переводом строки, который находится в конце каждой строки (мне неизвестно)
Select Case Wscript.Arguments.Count
case 1:
strInput = GetFile(WScript.Arguments(0))
RemoveUnwantedLines strInput, strInput
RemoveBlankLines strInput
case 2:
strInput = GetFile(WScript.Arguments(0))
strOutput = Wscript.Arguments(1)
RemoveUnwantedLines strInput, strOutput
RemoveBlankLines strOutput
End Select
Function GetFile(strDirectory)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strDirectory)
dateLastModified = Null
strFile = ""
For Each objFile in objFolder.Files
If IsNull(dateLastModified) Then
dateLastModified = objFile.DateLastModified
strFile = objFile.Path
ElseIf dateLastModified < objFile.DateLastModified Then
dateLastModified = objFile.DateLastModified
strFile = objFile.Path
End If
Next
GetFile = strFile
End Function
Sub RemoveUnwantedLines(strInputFile, strOutputFile)
'Open the file for reading.
Set objFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(strInputFile,1)
'Read the entire file into memory.
strFileText = objFile.ReadAll
'Close the file.
objFile.Close
'Split the file at the new line character. *Use the Line Feed character (Char(10))
arrFileText = Split(strFileText,Chr(10))
'Open the file for writing.
Set objFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(strOutputFile,2,true)
'Loop through the array of lines looking for lines to keep.
For i = LBound(arrFileText) to UBound(arrFileText)
'If the line is not blank process it.
If arrFileText(i) <> "" Then
'If the line starts "5442", see if the next line is "6999".
If Left(arrFileText(i),4) = "5442" Then
'Make sure the next line exists (Don't want an out of bounds exception).
If i + 1 <= UBound(arrFileText)Then
'If the next line is not "6999"
If Left(arrFileText(i + 1), 4) <> "6999" Then
'Write the "5442" line to the file.
objFile.WriteLine(arrFileText(i))
End If
Else
'If the next line does not exist, write the "5442" line to the file (without a new line).
objFile.WriteLine(arrFileText(i))
End If
'If the line does not start with "6999" and the line does not start with "7999".
Elseif Left(arrFileText(i),4) <> "6999" AND Left(arrFileText(i),4) <> "7999" Then
'Write the line to the file.
objFile.WriteLine(arrFileText(i))
End If
End If
Next
'Close the file.
objFile.Close
Set objFile = Nothing
End Sub
Sub RemoveBlankLines(strInputFile)
Set objFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(strInputFile,1)
'Read the entire file into memory.
strFileText = objFile.ReadAll
'Close the file.
objFile.Close
'Split the file at the new line character.
arrFileText = Split(strFileText,VbNewLine)
Set objFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(strInputFile,2,true)
'Loop through the array of lines looking for lines to keep.
For i = LBound(arrFileText) to UBound(arrFileText)
'If the line is not blank.
if arrFileText(i) <> "" Then
'If there is another element.
if i + 1 <= UBound(arrFileText) Then
'If the next element is not blank.
if arrFileText(i + 1) <> "" Then
'Write the line to the file.
objFile.WriteLine(arrFileText(i))
Else
'Write the line to the file (Without a blank line).
objFile.Write(arrFileText(i))
End If
Else
'Write the line to the file (Without a blank line).
objFile.Write(arrFileText(i))
End If
End If
Next
'Close the file.
objFile.Close
Set objFile = Nothing
End Sub