循环浏览子目录中的文件夹并合并文本文件 [英] Loop through folders in subdirectories and combine text files

查看:97
本文介绍了循环浏览子目录中的文件夹并合并文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历子目录中的文件夹,并将所有文本文件合并为一个文件.我在网上找到了一些答案,但似乎都没有用.任何帮助深表感谢.我提供了以下内容.在下面的示例中,DummyFolder具有多个包含.txt files的子目录,这些子目录需要合并为1个文件.昨天我有代码3可以工作,但是以某种方式我做了一些更改,并且由于某种原因它不再起作用.

I am wanting to loop through folders within a subdirectory and combine all text files into one file. I found some answers online but none seems to work. Any help is much appreciated. I have provided what I've found below. In the example below the DummyFolder has multiple subdirectories that contain .txt files that need to be merged into 1 file. I got code 3 to work yesterday but somehow I changed something and it is no longer working for some reason.

代码1:

@echo off
set "header=C:\Users\user\Desktop\DummyFolder\Headings.txt"
set "folder=C:\Users\user\Desktop\DummyFolder\"
set "tempFile=%folder%\temp.txt"
for %%F in ("%folder%\*.txt") do (
   type "%header%" >"%tempFile%"
   type "%%F" >>"%tempFile%"
   move /y "%tempFile%" "%%F" >nul
)

还找到了此代码(代码2):

Also found this code (Code 2):

$startingDir = 'C:\Users\user\Desktop\DummyFolder\'
$combinedDir = 'C:\Users\user\Desktop\DummyFolder\CombinedTextFiles'

Get-ChildItem $startingDir -Recurse | Where-Object {
   $txtfiles = Join-Path $_.FullName '*.txt'
   $_.PSIsContainer -and (Test-Path $txtfiles)
} | ForEach-Object {
   $merged = Join-Path $combinedDir ($_.Name + '_Merged.txt')
   Get-Content $txtfiles | Set-Content $merged
}

还找到了此代码(代码3):

Also found this code (Code 3):

@echo on
set folder="C:\Users\user\Desktop\DummyFolder\"
for /F %%a in ('dir /b /s %folder%') do (
   if "%%~xa" == ".txt" (
      (echo/------------------------------
      type %%~a
      echo/)>>"%~dp0list.txt"
   )
)

推荐答案

在CMD中,您将执行以下操作:

In CMD you'd do something like this:

@echo off

set "basedir=C:\some\folder"
set "outfile=C:\path\to\output.txt"

(for /r "%basedir%" %f in (*.txt) do type "%~ff") > "%outfile%"

要在批处理文件中使用,您需要将%f更改为%%f,将%~ff更改为%%~ff.

For use in batch files you need to change %f to %%f and %~ff to %%~ff.

在PowerShell中,您将执行以下操作:

In PowerShell you'd do something like this:

$basedir = 'C:\some\folder'
$outfile = 'C:\path\to\output.txt'

Get-ChildItem $basedir -Include *.txt -Recurse | Get-Content |
    Set-Content $outfile

这篇关于循环浏览子目录中的文件夹并合并文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆