将文件夹中的每个文件移动到以该文件命名的自己的文件夹中的批处理脚本? [英] Batch script that moves each file in a folder into their own folders named after the file?

查看:341
本文介绍了将文件夹中的每个文件移动到以该文件命名的自己的文件夹中的批处理脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有

/folder/file1.txt
/folder/file2.jpg
/folder/file3.py

我要创建

/folder/file1/file1.txt
/folder/file2/file2.jpg
/folder/file3/file3.py

我有这个批处理文件(请小心运行),但大多数情况下都可以运行,但是如果文件名中包含空格,则文件夹名称将仅被命名为空格,因此不会移动文件在里面.

I have this batch file (be careful where you run it), which mostly works but if there is whitespace in the file name, the folder name will only be named up until the whitespace and so the file won't be moved inside of it.

此外,我只能通过在文件夹名称的末尾任意放置文件夹"一词或一些随机字符串来使它起作用,如果我排除了它,则由于某种原因它将无法工作.我在Windows 7上.

Also, I only got it to work by arbitrarily putting the word "Folder" or some random string at the end of the folder name, if I exclude that, for some reason it won't work. I'm on windows 7.

@echo off

for /f %%a in ('dir /a-d /b') do (
  if not "%%~dpnxa"=="%~dpnx0" call :func "%%~a"
)

goto :EOF

:func
set file=%~1
set dir=%file% Folder
md "%dir%" Folder 2>nul
move "%file%" "%dir%" 
goto :EOF

关于如何解决空白/名称问题的任何想法?预先感谢.

Any ideas on how to address the whitespace/name issues? Thanks in advance.

推荐答案

@echo off

for /f "usebackq delims=?" %%a in (`dir /a-d /b`) do (
  if not "%%~dpnxa"=="%~dpnx0" call :func "%%~a"
)

goto :EOF

:func
set file=%~1
set dir=%file% Folder
md "%dir%" Folder 2>nul
move "%file%" "%dir%" 
goto :EOF

通过设置delims =?您是说您的分隔符是?分割字符串,而不是空格字符,这使您可以读取带有空格的完整文件名. Usebackq意味着您改为在要运行的命令周围使用`,对我而言,这使阅读和理解嘿,我实际上正在执行此字符串"更加合乎逻辑.

By setting the delims=? you are saying that your delimiter is a ? to split up a string, instead of the whitespace character, which allows you to read full file names with spaces in them. Usebackq means that you instead use ` around the command to be ran, which to me, just makes it more logical to read and understand "Hey, I'm actually executing this string."

这篇关于将文件夹中的每个文件移动到以该文件命名的自己的文件夹中的批处理脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆