Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
993 views
in Technique[技术] by (71.8m points)

windows - Using command prompt batch files to move and automatically rename duplicate files

So, here's what I have: I created a small batch file to record the results of a ping test to a text file. What I want to do is run the batch file and move the results log to a specific folder on the Desktop automatically. Then, if the target filename exists, automatically rename accordingly. Meaning, if File1 exists, create File2, File3, so on and so forth. Here's what I have so far:

@echo off
color A
title Ping Test
:A
echo.
cls
ping google.com -n 4 > C:Users\%username%Desktoppingresults.txt
cls
:Question
echo.
echo You can find the results in C:Users\%username%Desktoppingresults.txt
echo Would you like to run this test again? (Y/N)
Set /p Choice=
if %choice% equ y goto :A
if %choice% equ n goto :Results
if %choice% neq y goto :Question
if %choice% neq n goto :Question
:Results
cls
echo Would you like to view the results of the test? (Y/N)
Set /p Choice=
if %choice% equ y goto :OpenResults
if %choice% equ n goto :Close
if %choice% neq y goto :Results
if %choice% neq n goto :Results
:Close
exit
:OpenResults
start C:Users\%username%Desktoppingresults.txt

And the move batch file looks like this:

@echo off
echo.
cd C:UsersDieselDesktop
move pingresults.txt PingResults
if exist pingresults.txt ren pingresults.txt=+1
Exit.

I don't want to overwrite the existing file, but rename it in succession. I can't find any helpful articles anywhere using only batch files, they all say to use vbs or php, a language I'm not familiar with

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To rename files to file1 [file2][...] and move it in a desktop folder:

@ECHO Off &SETLOCAL
FOR %%a IN (*.txt) DO CALL:processFile "%%~a"
goto:eof

:processFile
SETLOCAL
:loop
SET /a fileCounter+=1
SET "fileName=%~n1%filecounter%%~x1"
IF EXIST "C:Users\%username%Desktop\%fileName%" GOTO:loop
ECHO MOVE "%~1" "C:Users\%username%Desktop\%fileName%"
ENDLOCAL
goto:eof

Look at the output and remove the word echo before move if it looks good.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...