批处理脚本复制文件名?

时间:2011-05-26 18:54:04

标签: batch-file

我正在尝试创建一个批处理脚本:

  • 复制新文件的文件名
  • 在最后一行
  • 之前的文本文件中将每个文件名粘贴到一个新行中

例如: 我在文件夹中有名为Picture.JPG和Picture2.JPG的文件。 批处理需要复制文件名“Picture”和“Picture2”并将其粘贴到textfile.txt中,该文件已经有一个我不想覆盖的最后一行,所以它看起来像这样:

Picture
Picture2
This is the last line

请注意,我不希望复制.JPG扩展程序。

有什么想法吗?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

读取this question以提取文件名,因为输入在管道中获取ls或dir命令的输出,然后使用“>>”将其附加到textfiloe.txt操作

要附加到文件的开头,请检查this

答案 2 :(得分: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 是可以与最后一行匹配的术语。

答案 3 :(得分:0)

使用名为mylistofjpegfiles.txt的文本文件将以下内容粘贴到jpegs文件夹中的bat文件中:

::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