csvbatch-filevbscriptheader-row

Insert Header Row into CSV using SED / VBS


First post and apologies in advance for being a complete and utter newb. I have inherited something which I'm just trying to hack a solution for, I have zero knowledge in it. I have searched the forum and believe to have found a part-answer (sed command) however, I'm hitting an issue in getting it to run successfully.

I need for this to run on a Windows box and it was used previous for a simple replace in a .csv file, I now need to insert a header row instead.

I have a 'fixit.cmd' file, which contains this;

set batdir=C:\Sed\filepath\batch
set impdir=C:\Sed\filepath\import
set filename=xxx

:: to read as parameter, uncomment next line
:: set filename=%1

cscript //NoLogo %batdir%\sed.vbs 1i"ABC,123" < %impdir%\%filename%.csv > %impdir%\%filename%_fixed.csv
pause

I have a 'sed.vbs' file, which contains this;

Dim pat, patparts, rxp, inp
pat = WScript.Arguments(0)
patparts = Split(pat,"/")
Set rxp = new RegExp
rxp.Global = True
rxp.Multiline = False
rxp.Pattern = patparts(1)
Do While Not WScript.StdIn.AtEndOfStream
  inp = WScript.StdIn.ReadLine()
  WScript.Echo rxp.Replace(inp, patparts(2))
Loop

When I run the 'fixit.cmd' I receive the error;

sed.vbs(7, 1) Microsoft VBScript runtime error: Subscript out of range: '[number: 1]'

I'm assuming that points towards the 'sed.vbs' content only supportng the previous replace and / or my header row insert string being incorrect.

What amendments do I need to make within the 'sed.vbs' content and / or my header row insert string to successfully insert a header row?

Would really appreciate any / all support.


Solution

  • Change your batch file like this:

    set "batdir=C:\Sed\filepath\batch"
    set "impdir=C:\Sed\filepath\import"
    set "filename=xxx"
    
    REM to read as parameter, uncomment next line
    REM set filename=%1
    
    >%temp%\header.txt echo ABC,123
    copy /b "%temp%\header.txt" + "%impdir%\%filename%.csv" "%impdir%\%filename%_fixed.csv"
    pause
    

    The VBS file is not needed anymore.

    Some notes on the changes I made:

    The line >%temp%\header.txt echo ABC,123 creates a file with the header line.

    The copy command concatenates the two files (header and your file),as @luciole75w already wrote in a comment.