How to remove a prefix from multiple files?

余生颓废 提交于 2019-12-01 12:50:01

问题


I downloaded a lot of videos that are named like [site.com] filename.mp4 and I wanted to remove the prefix so that they are named like filename.mp4.

I tried a batch file with the following code:

ren "[site.com] *.mp4" "///////////*.mp4"

But the result was .com] filename.mp4 and can't rename anything beyond the dot, any ideas?


回答1:


@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f "tokens=1*delims=]" %%a IN (
 'dir /b /a-d "%sourcedir%\*" '
 ) DO IF "%%b" neq "" (
 FOR /f "tokens=*" %%h IN ("%%b") DO ECHO(REN "%sourcedir%\%%a]%%b" "%%h"
)

GOTO :EOF

You would need to change the setting of sourcedir to suit your circumstances.

The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(REN to REN to actually rename the files.

Perform a directory scan of the source directory, in /b basic mode /a-d without directories and tokenise each filename found - the part before the first ] to %%a and the remainder to %%b.

If %%b is not empty (ie. did not contain ]) then do nothing, therwise use the default token set (which includes space) and tokens=0 to strip the leading spaces from %%b into %%h, then build the original filename and rename.




回答2:


Just for completeness, a cmd.exe alternative:

For %A In ("*] *.*") Do @(Set "_=%A"&Call Ren "%A" "%_:*] =%")



回答3:


Use a for loop to split on the space in the name.

@echo off

:: Pass the file name in as an argument.
:: Split the full path into a directory and filename in case the folder has a space too
set "filepath=%~dp1"
set "filename=%~nx1"

:: Jump into the hosting directory, split the file name after the first space, and jump out
pushd %filepath%
for /f "tokens=1,*" %%A in ("%filename%") do ren "%filename%" "%%B"
popd



回答4:


Use parameter expansion with pattern replacement.

f='[site.com] filename.mp4'
mv "$f" "${f/\[site\.com\] /}"

Even Windows systems can execute a Bash.

http://www.mingw.org/wiki/msys

This is a for loop:

for f in *.mp4; then
  mv "$f" "${f/\[site\.com\] /}"
done


来源:https://stackoverflow.com/questions/43678548/how-to-remove-a-prefix-from-multiple-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!