2011-05-26 203 views
1

我試圖創建一個批處理腳本:批處理腳本複製文件名?

  • 複製新文件的文件名
  • 粘貼在每個文件名在一個文本文件中的新行的最後一行

對於前例如: 我有文件夾中名爲Picture.JPG和Picture2.JPG的文件。 批處理需要複製該文件名「圖片」,「圖片2」並將其粘貼在TextFile.txt的,已經有,我不希望覆蓋最後一行,所以會出現這樣的:

Picture 
Picture2 
This is the last line 

請注意,我不想複製.JPG擴展名。

任何想法?

回答

4

這應該工作,你需要把它放在一個cmd.file

for %%a in (*.jpg) do echo %%~na >> Tem.txt 
type textfile.txt >> tem.txt 
copy tem.txt textfile.txt 
del tem.txt 
+0

這是一個很好的開始!如果我想在兩行之間回顯文件名,該怎麼辦?現在它只會添加到文件的開頭,對吧?假設我想在「First Line」行和「Last line」行之間插入文件名,它將如何工作? – jiake 2011-05-27 17:26:21

1

閱讀this question來提取文件名,作爲輸入獲取管道中的ls或dir命令的輸出,然後使用「>>」運算符將其附加到textfiloe.txt中。

要附加到文件檢查開始this

+0

如果我需要將其追加在兩條線之間? 第一行 圖片 圖片2 最後一行 的想法是,每個新加入的線路,則應在最後一行之前正確的,但最後的畫面名字的話。 – jiake 2011-05-26 19:30:04

+0

我正在尋找批處理腳本解決方案,而不是bash。謝謝你嘗試! – jiake 2011-05-26 23:05:47

1

此腳本接受兩個參數:

  • %1 - 文本文件的名稱;

  • %2 - 工作目錄(其中存儲*.jpg文件)。

@ECHO OFF 

:: set working names 
SET "fname=%~1" 
SET "dname=%~2" 

:: get the text file's line count 
SET cnt=0 
FOR /F "usebackq" %%C IN ("%fname%") DO SET /A cnt+=1 

:: split the text file, storing the last line separately from the other lines 
IF EXIST "%fname%.tmp" DEL "%fname%.tmp" 
(FOR /L %%L IN (1,1,%cnt%) DO (
    SET /P line= 
    IF %%L==%cnt% (
    CALL ECHO %%line%%>"%fname%.tmplast" 
) ELSE (
    CALL ECHO %%line%%>>"%fname%.tmp" 
) 
)) <"%fname%" 

:: append file names to 'the other lines' 
FOR %%F IN ("%dname%\*.jpg") DO ECHO %%~nF>>"%fname%.tmp" 

:: concatenate the two parts under the original name 
COPY /B /Y "%fname%.tmp" + "%fname%.tmplast" "%fname%" 

:: remove the temporary files 
DEL "%fname%.tmp*" 

get the text file's line count部分只需通過所有行迭代,同時增加了櫃檯。如果您確切知道最後一行是什麼,或者您知道它必須包含某個子字符串(即使它只是一個字符),您可以使用其他方法。在這種情況下,你可以替換上面使用這種FOR循環FOR循環:

FOR /F "delims=[] tokens=1" %%C IN ('FIND /N "search term" ^<"%fname%"') DO SET cnt=%%C 

其中search term是可以通過的最後一行匹配術語。

+0

我確實知道最後一行是什麼,它是沒有引號的「」。我將「搜索術語」用作「」的FOR循環。但由於某種原因,該批次刪除指定的搜索字詞... – jiake 2011-05-27 21:23:28

0

粘貼低於JPEG文件夾中的bat文件有一個文本叫mylistofjpegfiles.txt:

::Build new list of files 
del newlistandtail.txt 2>nul 
for /f %%A in ('dir *jpg /b') Do (echo %%~nA >> newlistandtail.txt) 


:: Add last line to this new list 
tail -1 mylistofjpegfiles.txt >> newlistandtail.txt 


:: Build current list of files without last line 
del listnotail.txt 2>nul 
for /f %%A in ('tail -1 mylistofjpegfiles.txt') Do (findstr /l /V "%%A" mylistofjpegfiles.txt >> listnotail.txt) 

:: Compare old list with new list and add unmatched ie new entries 
findstr /i /l /V /g:mylistofjpegfiles.txt newlistandtail.txt >> listnotail.txt 

:: add last line 
tail -1 mylistofjpegfiles.txt >> listnotail.txt 

:: update to current list 
type listnotail.txt > mylistofjpegfiles.txt 

:: cleanup 
del newlistandtail.txt 
del listnotail.txt 
+0

尾部包含在資源工具包或bat代碼是在這裏: http://ss64.org/viewtopic.php?id=506 – jack 2011-05-27 13:24:26