3

I am making a batch script to move files based on their extension, so for example:
video.avi would go to Videos
text.txt would go to text files I am using the drag and drop technique of getting the file path:
move %1 directory
how can I use if statements etc to test whether the file has a certain extension?
What I tried was:

if %1==*.txt (move to text files)

In any replies I get, could you please keep the answer generic (ie have (extension) instead of .txt) as I want to understand more easily
Thanks in advance

2

Solution

You need to use a specific variable modifier. Here's a working example:

if "%~x1" == ".ext" (echo File extension matches.)

Available modifiers

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string

Modifiers can be combined to get compound results. For example, %~nxI expands %I to a file name and extension only.

Further reading

  • Can't find modifiers documentation at the specified link. – Iulian Onofrei May 11 '19 at 11:18
0

You can completely ignore the If part. The MOVE command itself has support for wildcards, so the following code would work:

@echo off
move c:\source\*.avi d:\videos
move c:\source*.jpg d:\images

etcetera.

So you have all the files you need sorted in one place, and then just execute the batchfile.

If this isn't what you're after, then I've misunderstood what you're trying to accomplish.

  • I was using the move command as an example, the command I am using does not support wildcards, but I would've upvoted you if I had the rep – Kyle Apr 9 '14 at 13:55
0

Avoid the move and automatically find all text or video files using a for loop.

Code:

@echo off

cd\

for /r %systemdrive% %%a in (*.txt) do (

move "%%a" "yourpath/texts"  /y

)


for  /r %systemdrive% %%f in (*.avi) do (

move "%%f" "yourpath/videos" /y

)

You can have as many as you want, depending on files you need to move.

Hope that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.