2011-05-26 204 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