cmd批处理基于文件名合并文本文件以分隔txt文件

时间:2018-03-19 13:49:08

标签: windows batch-file cmd merge

我有一个包含10000个文本文件的文件夹。像这样的东西:

the end 1.txt
the end 2.txt
the end 3.txt
the blue one 1.txt
the blue one 2.txt
the blue one 3.txt
the blue one 4.txt
first letter 1.txt
first letter 2.txt
first letter 3.txt

我希望将每组文本文件(具有相同名称)合并到一个文本文件中。这样的事情 - 蓝色的all.txt - 首字母all.txt - 结束all.txt

我知道我可以使用commnad合并文本文件: copy * .txt allfiles.txt 我需要根据他们名字的一部分合并它们。

1 个答案:

答案 0 :(得分:0)

此代码假定文件名以SPACE结尾,然后是DIGITS,然后是#t; .txt'。如果没有,它可能不会做你想要的。如果您认为文件会正确连接,请从-WhatIf cmdlet中删除Add-Content

Get-ChildItem -File -Filter '*.txt' |
    ForEach-Object {
        if ($_ -match '(.*)\d+\.txt$') {
            $newname = $_.DirectoryName + '\' + $matches[1] + 'all.txt'
            Add-Content -Path $newname -Value (Get-Content $_) -WhatIf
        }
    }

如果必须从cmd.exe shell运行此命令,请将代码放入doit.ps1等文件中,然后在命令行或.bat文件中运行:

powershell -NoLogo -NoProfile -File doit.ps1
相关问题