如何将多个文本文件合并到' copy'在Windows Powershell中

时间:2016-11-02 12:23:29

标签: file powershell merge copy

我想将多个文本文件的内容合并到一个文本文件中。

我已尝试cat在此answer中解释过。但它很慢。 copy命令要快得多,但您必须将文件名放在加号分隔的字符串中,如:

cmd /c copy file1.txt + file2.txt + file3.txt + file1.txt all.txt

一些文件可以,但数千个文件没有。 所以我的想法是创建一个包含copy的文件输入的变量,如:

%list = 'file1.txt + file2.txt + file3.txt + file1.txt'

然后:

cmd /c copy %list all.txt

但这不起作用。

(我可以使用循环在Powershell中创建带有文件名的字符串。)

现在我想创建一个循环,将第一个文件与第二个文件合并,将生成的文件与第三个文件合并,依此类推。

cmd /c copy file1.txt + file2.txt merge1.txt

然后:

cmd /c copy merge1.txt + file3.txt merge2.txt

...

如何在Powershell的循环中执行此操作?

1 个答案:

答案 0 :(得分:0)

# Forces the creation of your content file
New-Item -ItemType File ".\all.txt" –force

# Build your file list here
$fileList = @('file1.txt', 'file2.txt', 'file3.txt')

# Assumes that all files are in the directory where you run the script
# You might have to adapt it to provide full path (e.g. $_.FullName)
$fileList | %{ Get-Content $_ -read 1000 } | Add-Content .\all.txt