How do I concatenate two text files in PowerShell?

前端 未结 11 1927
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 03:17

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

相关标签:
11条回答
  • 2020-11-28 03:32

    You could use the Add-Content cmdlet. Maybe it is a little faster than the other solutions, because I don't retrieve the content of the first file.

    gc .\file2.txt| Add-Content -Path .\file1.txt
    
    0 讨论(0)
  • 2020-11-28 03:33

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 03:39

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

    Get-Content files.* | Set-Content newfile.file
    
    0 讨论(0)
  • 2020-11-28 03:42

    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.

    0 讨论(0)
  • 2020-11-28 03:47

    To keep encoding and line endings:

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

    Note: AFAIR, whose parameters aren't supported by old Powershells (<3? <4?)

    0 讨论(0)
提交回复
热议问题