How do I concatenate two text files in PowerShell?
Simply use the Get-Content
and Set-Content
cmdlets:
Get-Content inputFile1.txt, inputFile2.txt | Set-Content joinedFile.txt
You can concatenate more than two files with this style, too.
If the source files are named similarly, you can use wildcards:
Get-Content inputFile*.txt | Set-Content joinedFile.txt
Note 1: PowerShell 5 and older versions allowed this to be done more concisely using the aliases cat
and sc
for Get-Content
and Set-Content
respectively. However, these aliases are problematic because cat
is a system command in *nix systems, and sc
is a system command in Windows systems - therefore using them is not recommended, and in fact sc
is no longer even defined as of PowerShell Core (v7). The PowerShell team recommends against using aliases in general.
Note 2: Be careful with wildcards - if you try to output to inputFiles.txt
(or similar that matches the pattern), PowerShell will get into an infinite loop! (I just tested this.)
Note 3: Outputting to a file with >
does not preserve character encoding! This is why using Set-Content
is recommended.
Do not use >
; it messes up the character encoding. Use:
Get-Content files.* | Set-Content newfile.file