Я первоначально задал вопрос, где мне требовалось удалить пробелы и заменить один с 13 пробелами разделителем вертикальной черты. Теперь у меня есть другой файл с 1 строкой очень длинного текста, в который мне нужно вставить вертикальную черту "|" разделитель после каждых 39 символов. Образец текста, с которым я пытаюсь работать:
000/042 BS CALIFORNIA 90001000/042 BS CALIFORNIA 90002000/042 BS CALIFORNIA 90003000/042 BS CALIFORNIA 90004000/042 BS CALIFORNIA
Я собираюсь написать пакетный файл, который может это сделать, поскольку я не смогу загрузить его на любой сервер sql без предварительной обработки с помощью SSIS и разделителей. Любая помощь приветствуется.
Обновлено: Код, который заменил пробелы и упростил работу с файлом, выглядит следующим образом:
Set Inp = wscript.Stdin
Set Outp = wscript.Stdout
Set regEx = New RegExp
regEx.Pattern = "\s{2,}"
regEx.IgnoreCase = True
regEx.Global = True
Outp.Write regEx.Replace(Inp.ReadAll, "|")
Я не уверен, как изменить это, чтобы разделитель вертикальной черты помещался после каждых 39 символов.
Спасибо сквошман. Может быть, я тоже немного не умею в SSIS, я думаю.
Спасибо всем за внимание к этому вопросу. Я публикую решение, которое я нашел, было достаточным для меня. Первоначально предполагалось вставить разделитель конвейера после каждых 39 символов. Но я думал в другом направлении. Я могу выполнить ту же задачу с источником плоского файла SSIS, где я выбираю параметр «Формат» как «Фиксированная ширина» и загружаю данные по мере необходимости.
Set Inp = wscript.Stdin
Set Outp = wscript.Stdout
Set regEx = New RegExp
regEx.Pattern = "(.{39,39})"
regEx.IgnoreCase = True
regEx.Global = True
Outp.Write regEx.Replace(Inp.ReadAll, "$1|")
http://download.microsoft.com/download/winscript56/Install/5.6/W982KMeXP/EN-US/scrdoc56en.exe
Файл справки VBScript. Найдите свойство pattern
. .
любой символ, кроме новой строки, минимум 39 и максимум 39, $1
заменить на то, что мы нашли плюс вертикальную черту.
Вот решение, основанное на коде от мой ответ до ваш оригинальный вопрос. В следующем скрипте снова используются те же методы для преодоления ограничений длины строки, обычно применимых к пакетным файлам (см. все пояснительные примечания rem
в коде):
@echo off
setlocal EnableExtensions DisableDelayedexpansion
rem // Define constants here:
set "_INPUT=.\PXZP_SND_XZ01_GFT10553.dat" & rem // (this is the input file)
set "_OUTPUT=.\R1.txt" & rem // (set to `con` to display the result on the console)
set "_TEMPF=%TEMP%\%~n0_%RANDOM%.tmp" & rem // (specifies a temporary file)
set /A "_FIX=39" & rem // (this specifies the fixed width)
set "_INSERT=|" & rem // (this is the insertion string)
rem // This stores an end-of-file character in a variable:
for /F %%E in ('forfiles /P "%~dp0." /M "%~nx0" /C "cmd /C echo 0x1A"') do set "_EOF=%%E"
rem /* The input file is going to be processed in a sub-routine,
rem which accesses the file content via input redirection `<`: */
< "%_INPUT%" > "%_OUTPUT%" call :PROCESS
endlocal
exit /B
:PROCESS
rem // Reset variables that store a partial string to be processed and a separator:
set "PART = " & set "SEP = "
setlocal EnableDelayedExpansion
:READ
rem /* At this point 1023 characters are read from the input file at most, until
rem a line-break or the end of the file is encountered:*/
set "NEW = " & set /P NEW = ""
rem // The read characters are appended to a string buffer that will be processed:
set "PART=!PART!!NEW!"
:LOOP
rem // Check whether or not the string buffer is empty:
if defined PART (
rem // String buffer is not empty, so split it in two parts using the fixed width:
set "LEFT=!PART:~,%_FIX%!" & set "RIGHT=!PART:~%_FIX%!"
) else (
rem /* String buffer is empty, hence reset both left and right string portions;
rem this step is necessary since splitting an empty string is not possible: */
set "LEFT = " & set "RIGHT = "
)
rem /* Jump back to read more characters in case the right string portion is empty,
rem unless the end of the file has already been reached, hence no more are left: */
if not defined RIGHT if defined NEW goto :READ
rem /* Skip processing when the left string portion is empty, which is the case when
rem no more data are left, so when the end of the file has already been reached: */
if defined LEFT (
rem /* Write to a temporary file the output string, which consists of an insertion
rem string (except for the very first time), the left string portion and an
rem end-of-file character; a line-break is automatically appended by `echo`: */
> "!_TEMPF!" echo(!SEP!!LEFT!%_EOF%
rem /* Copy the temporary file onto itself, but remove the end-of-file character
rem and everything after, then type the file content; this is a safe way of
rem echoing a string without a trailing line-break: */
> nul copy /Y /A "!_TEMPF!" + nul "!_TEMPF!" /B & type "!_TEMPF!"
rem // Set the insertion string now to skip it only for the first output:
set "SEP=!_INSERT!"
rem // Move the right string portion into the string buffer:
set "PART=!RIGHT!"
rem // Jump back to process the updated string buffer, hence to split it again:
goto :LOOP
)
endlocal
rem // Clean up the temporary file:
del "%_TEMPF%"
exit /B
Обратите внимание, что заданная фиксированная ширина должна быть положительным числом, меньшим примерно 8190 символов.
Странно, что вы не можете загрузить фиксированный текстовый файл в свою базу данных. Мои команды БД делают это каждый день для меня с пакетами SSIS.