1

I have a bunch of text files saved in a folder. I would like to merge them into one file, say "all.txt", with a blank line in between the content of each. I've seen this problem solved with bash here.

How do I accomplish a similar feat with Powershell?

KykyElric
  • 42
  • 1
  • 8

1 Answers1

0

Try this:

$sourcePath = "C:\Temp\*.txt"
$destFile = "C:\Temp\all.txt"
$encoding = "ASCII"

Remove-Item $destFile -ErrorAction SilentlyContinue

(Get-ChildItem -path $sourcePath) | 
    where-object { -not $_.PSIsContainer } |
    ForEach-Object {
        Get-Content $_; ""
    } |
    Out-File $destFile -Encoding $encoding

Not must to say. The get-childitem is in parens to ensure the list of files is gathered before all.txt is created. Directories are then filtered out with where-object { -not $_.PSIsContainer } and the each file is iterated over. The iterator outputs the file content followed by a blank line. Finally, the whole pipeline is re-directed to $destFile with the specified encoding.

andyb
  • 2,722
  • 1
  • 18
  • 17
  • I tried it, and it gave me a file with the file names of all the files in the directory, with blank lines in between. I would like the content of the files, not the file names. – KykyElric Sep 04 '17 at 04:42
  • That is odd. It works for me, showing the filename and then the file content. Did you copy/paste or re-type? – andyb Sep 04 '17 at 04:47
  • Editied to remove the filename. – andyb Sep 04 '17 at 04:51
  • It turns out I just typed the path incorrectly. Works smoothly; thanks a lot! – KykyElric Sep 04 '17 at 04:56
  • To read a file, you have to know the character encoding it was written with. This code [assumes ASCII](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/providers/filesystem-provider/get-content-for-filesystem?view=powershell-6) for each. It's unlikely that text files are ASCII, though the question asker would have to know. – Tom Blodget Sep 04 '17 at 14:32
  • The code makes no assumptions as to the encoding of the source files. It does force ASCII for the final output, but that's easily changed. I don't claim to be an expert in character encoding, but in a simple test of writing text files with different character encodings, PowerShell had no difficulty reading each one with a simple `get-content`. – andyb Sep 05 '17 at 00:57
  • (continued) - I do understand, though, that determining character encoding is far from trivial. – andyb Sep 05 '17 at 06:34