How do I concatenate two text files in PowerShell?

前端 未结 11 1947
没有蜡笔的小新
没有蜡笔的小新 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:56

    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.

提交回复
热议问题