How do I concatenate two text files in PowerShell?

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

    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
    
    0 讨论(0)
  • 2020-11-28 03:49

    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".

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

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

    gci *.log | sort LastWriteTime | % {$(Get-Content $_)} | Set-Content result.log
    
    0 讨论(0)
  • 2020-11-28 03:55

    I think the "powershell way" could be :

    set-content destination.log -value (get-content c:\FileToAppend_*.log )
    
    0 讨论(0)
  • 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.

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