[英]batch rename files according to filenames in another folder with powershell
[英]Rename all files in folder using batch or powershell run from batch
我在一個文件夾中有隨機文件名和擴展名的文件,文件夾中還有另一個包含* .htm擴展名的隨機文件名。 我想重命名文件夾中每個隨機文件的所有文件名,以匹配一個* .htm文件,同時保留每個隨機文件的正確擴展名。
因此,當運行批處理文件時,將檢測到諸如“我的文件名.HTM”之類的文件,並將以下文件重命名為:
“ test.doc”重命名為“我的文件名.doc”
“ anyfile.jpg”重命名為“我的文件名.jpg”
“ text.txt”重命名為“我的文件名.txt”
我努力了
Rename "*.*" "*.htm"
沒有成功。 * .HTM文件可以是任何未知的文件名,但始終包含HTM擴展名,並且它始終是文件夾中唯一具有HTM擴展名的文件。 然后,我將從命令行運行批處理文件。
簡潔的批處理文件:
for %%f in (*.htm) do set name=%%~nf
ren * "%name%.*"
與n01d的答案相同。 另外,不要將批處理文件放在同一目錄中。
編輯:
這是一個示例會話,顯示該批處理文件將所有文件重命名為.htm文件的名稱:
D:\tmp\kktmp>dir
Volume in drive D has no label.
Volume Serial Number is 4EDE-41E1
Directory of D:\tmp\kktmp
14/07/2016 12:06 <DIR> .
14/07/2016 12:06 <DIR> ..
14/07/2016 12:05 0 Author Name - Book Title - The Billionaires Revenge.htm
14/07/2016 12:06 0 Book Title - The Billiona - Author Name.azw3
14/07/2016 12:06 0 Book Title - The Billiona - Author Name.epub
14/07/2016 12:06 0 Book Title - The Billiona - Author Name.mobi
14/07/2016 12:06 0 Book Title - The Billiona - Author Name.pdf
5 File(s) 0 bytes
2 Dir(s) 52,725,227,520 bytes free
D:\tmp\kktmp>type ..\t.bat
for %%f in (*.htm) do set name=%%~nf
ren * "%name%.*"
D:\tmp\kktmp>..\t.bat
D:\tmp\kktmp>for %f in (*.htm) do set name=%~nf
D:\tmp\kktmp>set name=Author Name - Book Title - The Billionaires Revenge
D:\tmp\kktmp>ren * "Author Name - Book Title - The Billionaires Revenge.*"
D:\tmp\kktmp>dir
Volume in drive D has no label.
Volume Serial Number is 4EDE-41E1
Directory of D:\tmp\kktmp
14/07/2016 12:37 <DIR> .
14/07/2016 12:37 <DIR> ..
14/07/2016 12:06 0 Author Name - Book Title - The Billionaires Revenge.azw3
14/07/2016 12:06 0 Author Name - Book Title - The Billionaires Revenge.epub
14/07/2016 12:05 0 Author Name - Book Title - The Billionaires Revenge.htm
14/07/2016 12:06 0 Author Name - Book Title - The Billionaires Revenge.mobi
14/07/2016 12:06 0 Author Name - Book Title - The Billionaires Revenge.pdf
5 File(s) 0 bytes
2 Dir(s) 52,724,703,232 bytes free
像這樣:
$files = Get-ChildItem -Path D:\TEST_123
$htmBaseName = $files | where {$_.Extension -eq '.htm'} | select -ExpandProperty BaseName
foreach ($f in $files) {
if ($f.Extension -ne '.htm') {
Rename-Item -Path $f.FullName -NewName ($htmFileName + $f.Extension)
}
}
但是要小心:如果有多個具有相同擴展名的文件。 您將得到一個錯誤Cannot create a file when that file already exists
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.