Noct.
Noct.

Reputation: 3

Create directories based on filename substrings and move the files into them

I need some help automating a dull process.

I am collecting bilingual texts and I use prefixes in order to specify what language the given text contains.

A sample list would look like this:

IT 6875.pdf
EN 6875.pdf
IT sT5ezt.pdf
EN sT5ezt.pdf

I then manually create individual folders for a certain file pair. The output is:

6875
---IT 6875.pdf
---EN 6875.pdf

sT5ezt
---IT sT5ezt.pdf
---EN sT5ezt.pdf

I found a way to automatically create folders by using a .bat file named "organize.bat" I place in the target directory. I can create a folder for every file, and move the file into its folder. However, this is only useful in situations where I am not dealing with a bilingual file pair, but with a file containing both languages that I later edit into two files.

The syntax for this process is:

@echo off
for %%i in (*) do (
 if not "%%~ni" == "organize" (
  md "%%~ni" && move "%%~i" "%%~ni"
 )
)

I now wish adapt this task to the process mentioned on top.

  1. Skip the "IT" or "EN" prefix
  2. Select the whole file name after the prefix, until the extension .pdf
  3. Create and name folder after this selection
  4. Move file pairs into folders

After trying many different options I found here, I decided to post this query because I cannot wrap my head around this.

Upvotes: 0

Views: 261

Answers (1)

Magoo
Magoo

Reputation: 79982

 if not "%%~ni" == "organize" (
  for /f "tokens=1*" %%b in ("%%~ni") do (
   md "%%~c" 2>nul
   move "%%~i" "%%~c"
  )
 )

The name part of the file (eg. IT 6875) is tokenised using the space as a delimiter (by default), setting %%b to IT and %%c to 6875

see for /? from the prompt for more details - or many examples on SO.

The 2>nul ensures the next 6875 encountered does not raise a visible directory already exists error message.

Upvotes: 1

Related Questions