0

After considering using VBScript to merge files - see Do I need to use WMI in order to merge text files in VBScript? - I finally ended up using the DOS command COPY /B with appropriate pattern (and matching file names/extensions).

Note: the /B flag prevents weird behaviour with EOL (diff. CR/LF/CRLF) & EOF (had some SUB char appearing) characters.

But now I wonder: is there a way to also delete the merged files at the same time, provided that the whole merge process succeeded (important)?

Either using the same command - but that seems unlikely, given the COPY /? help - or any another DOS command, in combination or in full replacement?

maxxyme
  • 2,164
  • 5
  • 31
  • 48
  • 2
    `copy /B "file1.ext" + "file2.ext" "merged.ext" && del "file1.ext" "file2.ext"`? – aschipfl Jul 08 '19 at 17:48
  • @aschipfl the thing is I have an unknown number of "fileX.ext"... (and with long filenames too) so basically I'm building my command string like `"COPY /B """ & long_file_name_variable & ".index.ext""" """ & long_file_name_variable & """.ext"`. I did this because I'm afraid the command string would be too long to be 1/ executed 2/ output for debug. – maxxyme Jul 09 '19 at 10:03
  • 1
    What about `copy /B "file*.ext" "merged.ext" && del /Q "file*.ext"` (given you really want to merge all files into a single one and the order does not matter)? Or you use a [`for` loop](https://ss64.com/nt/for.html) to enumerate the files and use `copy` once per iteration... – aschipfl Jul 09 '19 at 11:01
  • The order **does** matter, but as I've constructed ever (partial) file name with a common prefix + an index + finally the same extension (e.g. `longfilename.001.ext`, `longfilename.002.ext`, & so on) I assume the COPY command sort them alphabetically before merging (and it works as espected). – maxxyme Jul 09 '19 at 13:57
  • 1
    Alright; it is the file system that returns the files sorted (like NTFS) or not (like FAT); to force alphabetic sorting you could do this: `set "FLAG=" & for /F "delims= eol=|" %F in ('dir /B /A:-D /O:NE "longfilename.*.ext"') do @(if defined FLAG (copy /B "merged.ext" + "%F" "merged.ext") else (set "FLAG=#" & copy /Y "%F" "merged.ext")) && del "%F"` – aschipfl Jul 09 '19 at 14:07
  • OK, then as the scripts are meant to be used on recent computers (Windows 10) there's not FAT involved. Thanks for your detailed answer anyway. Just a quick question about it: why do you `set` with double quotes *around* the equal sign? – maxxyme Jul 09 '19 at 14:27
  • 2
    `set "VAR=Value"` is the preferred syntax to set an environment variable, because it protects special characters (like `&`, for instance) and it avoids unintended trailing white-spaces; the quotation marks themselves do not become part of the value; note that this syntax requires the [command extensions](https://ss64.com/nt/cmd.html) to be enabled (but this is the default setting anyway)... – aschipfl Jul 09 '19 at 14:37

0 Answers0