superfluousAM
superfluousAM

Reputation: 111

Split file in half to two new text files (command line/batch file)

I generated a text file with certificate info and am trying to split it in half so that the first half of the text will be saved to a key file as well as the other half to a certificate file. I was able to use

more +7 cert.txt > cert.crt

to save the bottom half to a new certificate file but am struggling on how to get the first half into a new key file.

This is being done via a batch script that is sent to and executed on a Windows machine remotely so it needs to be done just with the built in commands from Windows.

Example:

-----BEGIN PRIVATE KEY-----
sample key data
sample key data
sample key data
sample key data
sample key data
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
sample cert data
sample cert data
sample cert data
sample cert data
sample cert data
-----END CERTIFICATE-----

Upvotes: 1

Views: 1377

Answers (1)

aschipfl
aschipfl

Reputation: 34899

You can use findstr /N to precede every line read from the file cert.txt with its line number and a colon and a for /F loop to iterate through these augmented lines. You can then redirect every single line (with the prefix removed) into the respective output file depending on the current line number:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "FULLFILE=cert.txt" & rem // (combined input file)
set "KEY_FILE=cert.key" & rem // (output key file)
set "CERTFILE=cert.crt" & rem // (output certificate file)
set "KEYLINES=7" & rem // (number of lines that belong to key file)
set "CERTLINE="  & rem // (first line of text belonging to cert. file)

if not defined KEYLINES set /A "KEYLINES=(1<<31)-1"
for /F "delims=" %%L in ('
    findstr /N /R "^" "%FULLFILE%" ^& ^
        ^> "%KEY_FILE%" break ^& ^
        ^> "%CERTFILE%" break
') do (
    set "LINE=%%L"
    set /A "LNUM=LINE"
    setlocal EnableDelayedExpansion
    if defined CERTLINE (
        if "!LINE:*:=!"=="!CERTLINE!" (
            endlocal
            set /A "KEYLINES=0"
            setlocal EnableDelayedExpansion
        )
    )
    if !LNUM! LEQ !KEYLINES! (
        >> "!KEY_FILE!" echo(!LINE:*:=!
    ) else (
        >> "!CERTFILE!" echo(!LINE:*:=!
    )
    endlocal
)
endlocal
exit /B

You can configure this script in two ways:

  1. Set KEYLINES to the number of lines (7) that belong to the key file, so that number of lines is output to the key file and all further lines are output to the certificate file; CERTLINE should be empty in this case.
  2. Set CERTLINE to the first line that belongs to the certificate file (-----BEGIN CERTIFICATE-----), so the lines are output to the key file until a line matches that string, in which case this line and all further ones are output to the certificate file; KEYLINES should be empty then.

Upvotes: 2

Related Questions