Search code examples
if-statementbatch-filemerge

Merge 2 files once the conditions are met


I currently merge csv files using rename.bat which is placed and executed in the directory holding those csv's.

The resulting file is created from a group of files which are constantly imported from an external source.

copy *.csv Pal.ORD.txt /b && del * .csv && ren *.txt *.csv

The problem is that, if the resulting file is not scanned, then I will have the merged files in one core file and the new individual files coming up and the code will just not merge them all.

I was thinking of making improvements such as:

IF EXIST PAL.ORD.CSV (copy *.csv Pal.ORD.txt /b && del * .csv && ren *.txt *.csv /EXCLUDE: PAL.ORD.CSV)
ELSE (copy *.csv Pal.ORD.txt /b && del * .csv && ren *.txt *.csv)

The problem with this new code is that I am not sure if the syntax is is correct, (I don't know where to place the EXCLUDE as well, just not to fuse the main core file with the new individual ones) and I would still have an issue to solve: to merge the two final files created.

Should I also include a type *.csv > concat_csv.txt at the end of the IF EXIST? This will also create an issue with the app that reads the file to import since it only allows csv files.


Solution

  • Your conditional check is correct in essence, but Batch doesn't support an /EXCLUDE option in the way you've used it. Your core file (PAL.ORD.CSV) needs to be excluded from the delete operation to prevent it from being merged each time incorrectly.

    @echo off
    setlocal
    
    if exist PAL.ORD.CSV (
        for %%F in (*.csv) do if /I not "%%F"=="PAL.ORD.CSV" copy /b "%%F"+PAL.ORD.TXT PAL.ORD.TXT >nul
        for %%F in (*.csv) do if /I not "%%F"=="PAL.ORD.CSV" del "%%F"
        ren PAL.ORD.TXT PAL.ORD.CSV
    ) else (
        copy *.csv PAL.ORD.TXT /b
        del *.csv
        ren PAL.ORD.TXT PAL.ORD.CSV
    )
    
    endlocal