'Concatenate two text files using command line (windows) and put the result in the first file

I have two text files I retrieve from some app that change their name on every load. I am writing a batch script where I want to Concatenate the two text files using command line (windows) and put the result in the first file.

example: F1_21032022.txt F2_21032022.txt ( the changing part is the numbers), I want to merge the result in F1_21032022.txt.

copy /b F1*.txt + F2*.txt F1*.txt => didn't work

more F1*.txt F2*.txt >> F1*.txt => didn't work as well

Please HELP !



Solution 1:[1]

This can be used at a cmd prompt or in a batch-file on windows. Note that the file number is selected from the filename by a regex capturing (\d*). This match is used to create the F2_ filename. The ECHO commands are just to create test files.

ECHO asdf`r`nqewr >"F1_000.txt"
ECHO 1234`r`n5678 >"F2_000.txt"

powershell.exe -NoLogo -NoProfile -Command ^
    Get-ChildItem -File -Filter 'F1_*.txt' ^| ^
        ForEach-Object { ^
            if ($_.Name -match 'F1_(\d*)\.txt') { ^
                $OtherFileName = """.\F2_$($Matches[1]).txt"""; ^
                if (Test-Path -Path $OtherFileName) { ^
                    Get-Content -Path $OtherFileName ^| Out-File -FilePath $_.FullName -Append -Encoding ascii ^
                } ^
            } ^
        }

This would be more easily written and understood by writing the script in PowerShell. It would avoid the contortions needed to write .bat file scripts. If you are on a supported Windows system, PowerShell is available.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lit