Вставьте разделитель трубы после каждых 39 символов - PullRequest
0 голосов
/ 09 апреля 2019

I Первоначально задал вопрос, где мне нужно было удалить пробелы и заменить одно на 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 символов.

Ответы [ 3 ]

4 голосов
/ 09 апреля 2019

Спасибо всем за внимание к этому вопросу.Я размещаю решение, которое я нашел, было достаточно для меня.Первоначально предполагалось вставить разделитель конвейера после каждых 39 символов.Но я думал в другом направлении.Я могу выполнить ту же задачу с источником плоских файлов служб SSIS, где я выбираю параметр «Формат» в качестве «Фиксированная ширина» и загружаю данные по мере необходимости.

enter image description here

3 голосов
/ 09 апреля 2019
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 замените на то, что мы нашли, плюс трубу.

1 голос
/ 10 апреля 2019

Вот решение, основанное на коде от моего ответа до вашего исходного вопроса .Следующий скрипт снова использует те же методы, чтобы преодолеть ограничения длины строки, обычно применяемые для пакетных файлов (см. Все пояснительные 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 символов.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...