How do I concatenate two text files in PowerShell?

2019-01-08 10:00发布

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, concatenate the variables together, and then write out the concatenated variable.

10条回答
在下西门庆
2楼-- · 2019-01-08 10:10

Do not use cat ... >; it messes up the character encoding. Use:

Get-Content files.* | Set-Content newfile.file

It took me hours to find this out.

查看更多
Anthone
3楼-- · 2019-01-08 10:23

I used:

Get-Content c:\FileToAppend_*.log | Out-File -FilePath C:\DestinationFile.log 
-Encoding ASCII -Append

This appended fine. I added the ASCII encoding to remove the nul characters Notepad++ was showing without the explicit encoding.

查看更多
成全新的幸福
4楼-- · 2019-01-08 10:24

You can simply use cat example1.txt, example2.txt | sc examples.txt. You can surely concatenate more than two files with this style, too. Plus, if the files are named similarly, you can use:

cat example*.txt | sc allexamples.txt

The cat is an alias for Get-Content, and sc is an alias for Set-Content.

Note 1: Be careful with the latter method - 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 2: Outputting to a file with > does not preserve character encoding! This is why using Set-Content (sc) is recommended.

查看更多
时光不老,我们不散
5楼-- · 2019-01-08 10:26

In cmd, you can do this:

copy one.txt+two.txt+three.txt four.txt

In PowerShell this would be:

cmd /c copy one.txt+two.txt+three.txt four.txt

While the PowerShell way would be to use gc, the above will be pretty fast, especially for large files. And it can be used on on non-ASCII files too using the /B switch.

查看更多
神经病院院长
6楼-- · 2019-01-08 10:27

Since most of the other replies often get the formatting wrong (due to the piping), the safest thing to do is as follows:

add-content $YourMasterFile -value (get-content $SomeAdditionalFile)

I know you wanted to avoid reading the content of $SomeAdditionalFile into a variable, but in order to save for example your newline formatting i do not think there is proper way to do it without.

A workaround would be to loop through your $SomeAdditionalFile line by line and piping that into your $YourMasterFile. However this is overly resource intensive.

查看更多
一纸荒年 Trace。
7楼-- · 2019-01-08 10:29

If you need to order the files by specific parameter (e.g. date time):

gci *.log | sort LastWriteTime | % {$(Get-Content $_)} | Set-Content result.log
查看更多
登录 后发表回答