2015-04-08 29 views
0

我正在嘗試編寫一個批處理腳本,它將駐留在目錄中的所有文本文件與名稱包含特定字符串遞歸。將所有文本文件遞歸地連接到最接近的父目錄的名稱中包含特定字符串的目錄中

在標有(x)的文件下面的例子應該合併,因爲他們最親密的父目錄的名稱已包括STRING

Directory 
|-- STRINGdirectory2 
| |-- textfile.txt  (x) 
| |-- anotherfile.txt (x) 
|-- anotherdirectory2 
| |-- textfile.txt 
|-- directory3 
| |-- STRINGdirectory3 
| | |-- file.txt  (x) 

如何才能做到這一點的名稱?

+0

你是什麼意思合併? 你的意思是把它們全部放在一個目錄中,還是你的意思是連接? –

+0

@rep_movsd我想連接它們。我會澄清。 – Hugo

回答

4
@echo off 
    setlocal enableextensions disabledelayedexpansion 

    set "root=c:\somewhere\Directory" 

    ( for /r "%root%" /d %%a in ("*string*") do (
      for %%b in ("%%~fa\*.txt") do (
       type "%%~fb" 
       echo(
      ) 
     ) 
    ) >"%root%\concatenated.txt" 2>nul 

給定根文件夾,包含在其名稱中指定的字符串,該文件夾內的每個txt文件其下每個文件夾,輸入文件

完整的for輸出被重定向到一個文件以保存「連接」數據。

+0

太棒了!每次添加後如何添加換行符? – Hugo

+0

@Hugo,回答已更新。 –

+0

不應該是 set root = c:\ somewhere \ Directory而不是 設置「root = c:\ somewhere \ Directory」 –

0

在這裏你去:

@echo off 
setlocal 
SET tempfile=%temp%\%RANDOM% 

if '%1' == '' goto usage 
if '%2' == '' goto usage 
if '%3' == '' goto usage 

if exist %3 del %3 
dir /S /B | find %2 > %tempfile% 

if '%4' == 'test' goto dryrun 

for /F %%i in (temp.txt) do type %%i >> "%3" 

goto end 

:dryrun 
type %tempfile% 
goto end 

:usage 

echo Usage %0 ^<dir^> ^<pattern^> ^<destination^> [test] 
echo Concatente all files inside ^<dir^> whose names have the substring ^<pattern^> into ^<destination^> 
echo Specify 'test' optionally the fourth argument for a dry run which will merely list the files 

:end 
if exist %tempfile% del %tempfile% 
1

MC ND has a great answer正確處理文件的最後一行可能沒有行結束符(\ n或\ r \ n)的可能性。如果他沒有ECHO(那麼,如果文件的第一行沒有行結束符,那麼文件的第一行可以追加到前一行文件的最後一行.MC ND的答案唯一的問題是它可以增加一個額外的文件之間的空行,即使在不需要的時候。

如果你知道你的所有文件有一個行終止底,然後有一個非常簡單的解決方案,它依賴於無證wildcard characters,而事實上,undocumented wildcards used with FINDSTR do not trigger output of file name prefixes

@echo off 
pushd "c:\your\root\path" 
>concatenated.txt 2>nul (for /r /d %%D in (*string*) do findstr "^" "<.txt") 

如果您知道某些文件可能缺少最後一行結束符,但所有文件都使用Windows標準\ r \ n行結束符,則可以使用以下內容來有條件地添加li只在需要時纔在文件之間使用ne終止符。 FINDSTR命令檢查文件是否包含不包含\ r(回車)的行。

@echo off 
pushd "c:\your\root\path" 
>concatenated.txt 2>nul (
    for /r /d %%D in (*string*) do for %%F in ("%%D\*.txt) do (
    type "%%F" 
    findstr /v "$" "%%F" >nul && echo(
) 
) 

如果你知道一些文件可能丟失最後行結束了,你覺得某些文件可能使用的\ n代替\ r \ n,那麼你可以使用我JREPL.BAT regular expression find/replace utility有條件地追加\ r \ n只根據需要。 JREPL.BAT是一個混合的JScript /批處理腳本,可以在任何Windows機器上從本機運行。

@echo off 
pushd "c:\your\root\path" 
>concatenated.txt 2>nul (
    for /r /d %%D in (*string*) do for %%F in ("%%D\*.txt) do (
    jrepl "$(?~\r?\n)" "\r\n" /m /x /f "%%F" 
) 
) 
+0

有很多問題,我通常在等待你使用'jrepl'的迴應,因爲它是工作,但在這種情況下,我沒有意識到它可以使用。真的很好,但我仍然不同意* *「無證」*術語。 –

相關問題