BluePrint
BluePrint

Reputation: 2134

Removing file in windows batch script not working

I'm trying to create a batch script for trimming 25 seconds from the beginning of all mp4 files in a folder. The batch script is located in the same folder as the files, and there is a folder called trimmed in the same folder. This is my script so far:

@echo off
setlocal DisableDelayedExpansion

:promptdel
set /p delorig=Delete original file (default no)? [Y/N]: 

if not defined delorig (
  set delorig=N
)

set "vartwo="&for /f "delims=YNyn" %%i in ("%delorig%") do set vartwo=%%i

if defined vartwo (
  echo Please state Y or N!
  goto :promptdel
)

for %%a in ("*.mp4") do (
  echo Starting %%a

  rem "Need to rename since file names may contain whitespaces"
  ren "%%a" "working.mp4"
  ffmpeg -loglevel panic -hide_banner -i "working.mp4" -ss 00:00:25.000 -c:v copy -c:a copy "trimmed\%%a"
  ren "working.mp4" "%%a"

  echo %delorig%
  if %delorig% == "Y" (del "%%a" /f /q)
  if %delorig% == "y" (del "%%a" /f /q)

  echo %%a finished!
)

pause

My problem is that the original file does not get removed regardless of if I input y/Y or n/N. What am I doing wrong?

Upvotes: 0

Views: 55

Answers (2)

Compo
Compo

Reputation: 38718

I have decided to include this answer, as I believe that the fix isn't technically the best way to deal with the issue you are having.

The best way would be to use the choice command, instead of allowing uncontrolled input data via set /p.

It is also, to my knowledge, not necessary to change a name containing spaces, especially as your ffmpeg code is already using doublequoted filenames.

Example:

@Echo Off
"%__AppDir__%choice.exe" /T 10 /D N /M "Delete original file [default No]" 
Set "delorig=%ErrorLevel%" 
For %%G In ("*.mp4") Do (Echo Starting %%G
    "ffmpeg.exe" -loglevel panic -hide_banner -i "%%G" -ss 00:00:25.000 -c:v copy -c:a copy "trimmed\%%G"
    If Not ErrorLevel 1 If %delorig% Equ 1 Del /F/Q "%%G"
    Echo %%G finished!)
Pause

Please note, that I have included the extension for ffmpeg to prevent accidental modification of %PATHEXT% from not running .EXE files. I would also suggest, if known/possible, that you use the full path to ffmpeg.exe, to ensure that possible %PATH%/directory/registry changes don't prevent it from being run, (as the code has not explicitly set a current directory). Additionally the code does not first ensure that a directory named trimmed exists in the current directory, so if ffmpeg cannot create it itself, you should probably perform a check, and/or create it first.

Upvotes: 0

RGuggisberg
RGuggisberg

Reputation: 4750

You quoted one side of the equation... but not the other. Change

  if %delorig% == "Y" (del "%%a" /f /q)
  if %delorig% == "y" (del "%%a" /f /q)

to

  if "%delorig%"=="Y" (del "%%a" /f /q)
  if "%delorig%"=="y" (del "%%a" /f /q)

or better yet... do this to make the comparison case-insensitive.

if /i "%delorig%"=="Y" del "%%a" /f /q

Upvotes: 1

Related Questions