问题描述
|
我正在尝试创建一个批处理脚本,该脚本:
复制新文件的文件名
将每个文件名粘贴到文本文件中最后一行之前的新行中
例如:
我的文件夹中有名为Picture.JPG和Picture2.JPG的文件。
该批处理需要复制文件名\“ Picture \”和\“ Picture2 \”并将其粘贴到textfile.txt中,该文件已经有我不想覆盖的最后一行,因此将显示为:
Picture
Picture2
This is the last line
请注意,我不想复制.JPG扩展名。
有任何想法吗?
解决方法
这应该可行,您需要将其放在cmd.file中
for %%a in (*.jpg) do echo %%~na >> Tem.txt
type textfile.txt >> tem.txt
copy tem.txt textfile.txt
del tem.txt
,阅读此问题以提取文件名,作为输入在管道中获取ls或dir命令的输出,然后使用\“ >> \”运算符将其附加到textfiloe.txt。
要附加到文件的开头,请检查此
,该脚本接受两个参数:
%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
是可以与最后一行匹配的术语。
,将以下内容粘贴到jpegs文件夹中的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