I am trying to replicate the functionality of the cat
command in Unix.
I would like to avoid solutions where I explicitly read both files into variables
To concat files in command prompt it would be
type file1.txt file2.txt file3.txt > files.txt
PowerShell converts the type
command to Get-Content
, which means you will get an error when using the type
command in PowerShell because the Get-Content
command requires a comma separating the files. The same command in PowerShell would be
Get-Content file1.txt,file2.txt,file3.txt | Set-Content files.txt
You can do something like:
get-content input_file1 > output_file
get-content input_file2 >> output_file
Where >
is an alias for "out-file", and >> is an alias for "out-file -append".
If you need to order the files by specific parameter (e.g. date time):
gci *.log | sort LastWriteTime | % {$(Get-Content $_)} | Set-Content result.log
I think the "powershell way" could be :
set-content destination.log -value (get-content c:\FileToAppend_*.log )
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, but these aliases are deprecated and even removed in new versions, so it's best to avoid them.
Note 2: Be careful with wildcards - if you try to output to examples.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.