2017-05-17 159 views
1

我有兩個.txt文件。一個包含數字,另一個包含文件路徑。我想將這兩個文件合併爲一個.csv文件。組合是基於數字(來自nrs.txt)在文件路徑的字符串(nodups.txt)中。批處理文件中的嵌套/ F循環和If語句

現在我對這個下面的代碼:

@setlocal enableextensions enabledelayedexpansion 

for /F %a IN (Output\nrs.txt) DO (
    SET "nrs=%a" 

    for /F %b IN (Output\nodups.txt) DO (
     SET "pathstring=%b" 
     SET csvdelim=, 
     IF NOT x!pathstring:%nrs%=""!==x%pathstring% %nrs%,%pathstring%>>new2017.txt 
    ) 
) 

@endlocal 

不過,我一直有與代碼以下問題:

  1. 的pathstring似乎從來就沒設置。 (當我運行沒有if語句的代碼時,nrs變量被設置,但是the pathstring is set to %b)。我已經在這裏看到了很多可能的解決方案,但似乎沒有一個適用於我(設置變量,如!var!和使用usebackq)。
  2. 第二個for循環中的IF語句獲取以下錯誤消息=""!==x%pathstring% was unexpected at this time=""應該刪除nr。從路徑(如果有的話)。當我用其他東西替換「」時,它仍然不起作用。

文件內容是:

文件nrs.txt:

12345 
12245 
16532 

nodubs.txt:

C:\tmp\PDF_16532_20170405.pdf 
C:\tmp\PDF_1234AB_20170405.pdf 
C:\tmp\PDF_12345_20170506.pdf 

所需的輸出:

12345, C:\tmp\PDF_12345_20170506.pdf 
16532, C:\tmp\PDF_16532_20170405.pdf 

我真的很希望有人能幫助我解決這個問題!

回答

1

該解決方案使用不同的方法,基於arrays

@echo off 
setlocal EnableDelayedExpansion 

rem Load array from nodubs.txt file 
pushd "Output" 
for /F "tokens=1,2* delims=_" %%a in (nodubs.txt) do set "nodubs[%%b]=%%a_%%b_%%c" 

rem Process nrs.txt file and show output 
(for /F %%a in (nrs.txt) do (
    if defined nodubs[%%a] echo %%a, !nodubs[%%a]! 
)) > new2017.txt 
+0

我更喜歡這個解決方案,因爲它對我來說更加清楚,至於它是如何工作的(以及是否有任何改變,我知道在哪裏做出調整)。但是,如果我像這樣運行它,我不會得到任何輸出。如果我刪除了@echo off,我得到: 'C:\ Path \ Output>(如果定義了nodubs [12345] echo 12345,!nodubs [12345]!) C:\ Path \ Output> (如果定義的結節[12245]回波12245,結節[12245]!) C:\ Path \ Output>(如果定義結節回波16532,!結節!)' – Coen

+0

您可以刪除括號它包圍了for和重定向,也就是說,通過'for ...)'改變'(for ...))> new2017.txt',然後在echo的末尾插入'>> new2017.txt'重定向%% a,...'行。 – Aacini

+0

非常感謝! – Coen

0
  • 在變量的批處理文件中需要兩個百分號。
  • 有沒有必要把%%A放入一個變量,直接使用它。

@setlocal enableextensions enabledelayedexpansion 
for /F %%a IN (Output\nrs.txt) DO (
    findstr /i "_%%a_" Output\nodups.txt >NUL 2>&1 || >>new2017.txt Echo %%a 
) 
@endlocal 
  • 相反的第二對,我會使用FINDSTR搜索nrs.txt的封閉在下劃線的條目。
  • 如果沒有找到使用故障履歷執行||寫入新文件。
+0

我很抱歉,我想我是不清楚。我需要在新文件中追加路徑和數字。你用自己的方式可以玩嗎?也出於某種原因,%% a給了我一個'%% a在這個時候是意外的'錯誤。這就是爲什麼我使用%a(看起來工作正常) – Coen

+0

請編輯您的問題,以根據示例中使用的樣本nrs.txt和nodubstxt – LotPings

+0

'%a'和'%b'包含您希望的輸出樣本。在批處理文件中不起作用,並且因爲您的文章是標記爲批處理文件,所以@LotPings的用法是正確的。 – Compo

0

根據變更後的預備案另一個答案。

@Echo on 
Pushd Output 
for /F "tokens=1-3 delims=_" %%A IN (
    ' findstr /G:nrs.txt nodubs.txt' 
) DO >>"..\new2017.txt" Echo %%B, %%A_%%B_%%C 
Popd 

輸出樣本:

> type ..\new2017.txt 
16532, C:\tmp\PDF_16532_20170405.pdf 
12345, C:\tmp\PDF_12345_20170506.pdf