moving a file based on its extension in BATCH

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

Kyle

Posted 2014-04-09T12:38:47.427

Reputation: 33

Answers

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

and31415

Posted 2014-04-09T12:38:47.427

Reputation: 13 382

Can't find modifiers documentation at the specified link. – Iulian Onofrei – 2019-05-11T11:18:50.833

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.

LPChip

Posted 2014-04-09T12:38:47.427

Reputation: 42 190

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 – 2014-04-09T13:55:40.010

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.

mordex

Posted 2014-04-09T12:38:47.427

Reputation: 1