Replace old file with new file

2019-03-07 01:50发布

I am trying to write a script to replace old files content with new files content which is appearing in the following format:

Old file : something.txt
New file : something.txt.new

Old file need to replaced with New file contents
New File name to be rename without new
Old file need to be deleted

Below script is not working :Could you please rewrite:

@echo off
setlocal enabledelayedexpansion
set FOLDER_PATH=D:\test
for %%f in (%FOLDER_PATH%*) do if %%f neq %~nx0 (
    set basename=test
    ren *.txt.new !basename!.txt
)
PAUSE

i have many files in folder and need to iterate through each file,only i need is basename variable need to be filled with the name of the old file name in each iteration

3条回答
贼婆χ
2楼-- · 2019-03-07 02:35

Invalid question Invalid answer

source 1

@echo off
set FOLDER_PATH=D:\test
cd /d "%FOLDER_PATH%"
ren "*.txt.new" "*.txt"

source 2

@echo off
set FOLDER_PATH=D:\test
cd /d "%FOLDER_PATH%"
ren "*.txt" "*.txt.new"
查看更多
Melony?
3楼-- · 2019-03-07 02:42
@echo off
setlocal
set FOLDER_PATH=D:\test
for %%f in (%FOLDER_PATH%\*.new) do if "%%~ff" neq "%~f0" (
    ECHO move /Y "%%~ff" "%%~dpnf"
)
PAUSE

or

@echo off
setlocal
set FOLDER_PATH=D:\test
for %%f in (%FOLDER_PATH%\*.new) do if "%%~ff" neq "%~f0" (
    if exist "%%~dpnf" ECHO del "%%~dpnf"
    ECHO rename "%%~ff" "%%~nf"
)
PAUSE

Note that operational move (del and rename) commands are merely ECHOed for debugging purposes.

Also note that if "%%~ff" neq "%~f0" could be omitted iterating *.new files as %~f0 has an extension of .bat or .cmd (try echo %~x0 %~f0).

Resources (required reading):

查看更多
劫难
4楼-- · 2019-03-07 02:42
  1. You missed a \in %FOLDER_PATH%\*.
  2. You want to rename *.new files only, so why not using this pattern rather than *? If you are interested in files matching the pattern *.txt.new, then specify this instead of *.
  3. There is no need for variable basename; simply use %%~nf to remove the (last) suffix (.new).
  4. The ren command throws an error in case the target file already exists; since you want it to be overwritten, use move /Y instead. Add > nul to hide the summary 1 file(s) moved..
  5. Remove the if query after having resolved item 2.

All in all, your script can be reduced to:

@echo off
set "FOLDER_PATH=D:\test"
rem // Ensure to specify the correct pattern, `*.new` or `*.txt.new`:
for %%f in ("%FOLDER_PATH%\*.txt.new") do (
    > nul move /Y "%%~f" "%%~nf"
)
pause
查看更多
登录 后发表回答